python设计GUI简单了解

本系列来源于B站视频。UP主为IT搬運工,系列视频为[小甲鱼]零基础入门学习python点我直达

GUI的终极选择:TKinter

Lesson 1

import tkinter as tk

#根窗口
app = tk.Tk()
app.title("Moliam")
#Label组件
theLabel = tk.Label(app, text="Moliam GUI")
#自动调节尺寸
theLabel.pack()
#串口的主事件循环
app.mainloop()

运行后拉伸显示如下

img

视频结束完工的代码

import tkinter as tk


# 封装成类
class APP:
    def __init__(self, master):
        # 复杂的布局里将组件分组
        frame = tk.Frame(master)
        # 不填参数默认调中
        # 设置为左边
        frame.pack(side=tk.LEFT, padx=10, pady=10)
        # fg前景色 bg背景色
        self.hi_there = tk.Button(frame, text='Hi', bg='#abc', fg='blue', command=self.say_hi)
        self.hi_there.pack()

    #将方法设置为static
    @staticmethod
    def say_hi():
        print('moliam 真帅')


# 根窗口
root = tk.Tk()
app = APP(root)
root.title("Moliam")

# 串口的主事件循环
root.mainloop()

Lesson 2

Label示例

from tkinter import *

root = Tk()
#justify 左对齐
textLabel = Label(root, text='Warning\nWhat are you doing', justify=LEFT)
textLabel.pack(side=LEFT)
# 图片
photo = PhotoImage(file='photo/0906-张俊秋-线稿图.png')
imglabel = Label(root, image=photo)
imglabel.pack(side=RIGHT)

mainloop()
from tkinter import *

root = Tk()
photo = PhotoImage(file='photo/0906-张俊秋-线稿图.png')
theLabel = Label(root,
                 text='Moliam 线稿',
                 justify=LEFT,
                 image=photo,
                 compound=CENTER,
                 font=('华康少女字体', 15),
                 fg='#000')
theLabel.pack()
mainloop()

Button示例

from tkinter import *

root = Tk()


def callback():
    var.set('No, you are working')


frame1 = Frame(root)
frame2 = Frame(root)

#textvariable 支持的变量
var = StringVar()
var.set('What are you doing')

textLabel = Label(frame1,
                  textvariable=var,
                  justify=LEFT)
textLabel.pack(side=LEFT)
photo = PhotoImage(file='photo.png')
imglabel = Label(frame1, image=photo)
imglabel.pack(side=RIGHT)

theButton = Button(frame2, text='I am do nothing', command=callback)
theButton.pack()

frame1.pack(padx=10, pady=10)
frame2.pack()

mainloop()

Lesson 3

Checkbutton

from tkinter import *

root = Tk()
v = IntVar()
# 打勾的选择框
c = Checkbutton(root, text='测试一下', variable=v)
c.pack()

la = Label(root, textvariable=v)
la.pack()

mainloop()
from tkinter import *
root = Tk()

GIRLS = ['西施', '貂蝉', '王昭君', '杨玉环']
v = []

for girl in GIRLS:
    v.append(IntVar())
    #-1拿到最后一个元素
    b = Checkbutton(root, text=girl, variable=v[-1])
    #左对齐(东,W)
    b.pack(anchor=W)

mainloop()

Radiobutton

from tkinter import *
root = Tk()

v = IntVar()
#默认值为1
v.set(1)
#单选框,只能选择一个
#variable 只能设置同一个变量
Radiobutton(root, text="One", variable=v, value=1).pack(anchor=W)
Radiobutton(root, text="Two", variable=v, value=2).pack(anchor=W)
Radiobutton(root, text="Three", variable=v, value=3).pack(anchor=W)

mainloop()
from tkinter import *
root = Tk()

group = LabelFrame(root, text="最好看的美女是?")
group.pack()

BEAUTY = ['西施', '貂蝉', '王昭君', '杨玉环']

v = IntVar()
v.set(1)
i = int('1')
for beauty in BEAUTY:
    #拿到最后一个元素
    b = Radiobutton(group, text=beauty, variable=v, value=i)
    i += 1
    #左对齐(东,W)
    b.pack(anchor=W)

mainloop()

Lesson 4

Entry

from tkinter import *
root = Tk()

e = Entry(root)
#输入框清空
e.delete(0, END)
#输入框写入
e.insert(0, "Moliam")
e.pack()

mainloop()

小练习

def show():
    print("域名:%s" % worksE.get())
    print("拥有者: %s" % authorsE.get())


#grid和pack一样都是进行打包显示,但是实现的结果不尽相同
#在第0行第0列
works = Label(root, text="域名:").grid(row=0, column=0)
authors = Label(root, text="拥有者:").grid(row=1, column=0)

#Entry可以进行输入验证,具体百度
worksE = Entry(root)
worksE.grid(row=0, column=1, padx=10, pady=5)
worksE.insert(0, "moliam.space")
#show="*"代表每输入一个字符便以*显示
authorsE = Entry(root, show='*')
authorsE.grid(row=1, column=1, padx=10, pady=5)
authorsE.insert(0, "moliam")

button1 = Button(root, text="获取信息", command=show, width=10)
button1.grid(row=3, column=0, sticky=W, padx=10, pady=5)
#root.quit 退出GUI
button2 = Button(root, text="退出", command=root.quit, width=10)
button2.grid(row=3, column=1, sticky=E, padx=10, pady=5)

mainloop()

运行结果

img

Lesson 5

Listbox

from tkinter import *
master = Tk()

#BROWSE 模式,共有单选(SINGLE,BROWSE),多选(MULTIPLE,EXTENDED)  4种模式,每种模式各有不同,区别:www.baidu.com
theLB = Listbox(master, selectmode=BROWSE)


for i in ["西瓜", "冬瓜", "南瓜", "傻瓜"]:
    theLB.insert(END, i)
#ACTIVE为当前的选项
thebutton = Button(master, text="delete", command=lambda x=theLB: x.delete(ACTIVE))

theLB.pack()
thebutton.pack()

mainloop()

Scrollbar

from tkinter import *
root = Tk()

sb = Scrollbar(root)
sb.pack(side=RIGHT, fill=Y)

#当滚动时,修改滚动条的位置
theLB = Listbox(root, yscrollcommand=sb.set)
for i in range(21):
    theLB.insert(END, i)
# fill=X 当GUI窗体大小发生变化时,在X方向跟随GUI窗体变化
# fill=Y 当GUI窗体大小发生变化时,在Y方向跟随GUI窗体变化
# fill=BOTH 当GUI窗体大小发生变化时,在X、Y两方向跟随GUI窗体变化
#Pack只会吝啬地给出可以容纳组件的最小区域
theLB.pack(side=LEFT, fill=X)
#当拖动滚动条变化时,修改listbos的显示
sb.config(command=theLB.yview)

mainloop()

Scale

from tkinter import *
root = Tk()
#在给定值内进行滑动选择
Scale(root, from_=0, to=20).pack()

mainloop()

Lesson 6

Text

from tkinter import *
root = Tk()
#平均30个字符宽度,2个字符高度
text = Text(root, width=30, height=30)
text.pack()

photo = PhotoImage(file="photo/image.png")


def button_fun():
    #text插入图片
    text.image_create(END, image=photo)


b1 = Button(text, text="剑来", command=button_fun)
#text插入按钮
text.window_create(INSERT, window=b1)

mainloop()

Lesson 7

Tags

from tkinter import *
root = Tk()

text = Text(root, width=30, height=10)
text.pack()

text.insert(INSERT, "Moliam is handsomest")
text.tag_add("tag1", "1.4", "1.8")
#新创建的tag样式会覆盖掉旧的tag
text.tag_config("tag1", background="#000", foreground="#fff")

mainloop()

Lesson 8

Canvas

from tkinter import *
root = Tk()

w = Canvas(root, width=200, height=100, background="#000")
w.pack()

w.create_line(0, 50, 200, 50, fill="blue")
#dash虚线
w.create_line(100, 0, 100, 100, fill="blue", dash=(10, 5))
w.create_rectangle(50, 25, 150, 75, fill='yellow')

mainloop()
from tkinter import *
root = Tk()

w = Canvas(root, width=200, height=100, background="#000")
w.pack()

line1 = w.create_line(0, 50, 200, 50, fill="blue")
#dash虚线
line2 = w.create_line(100, 0, 100, 100, fill="blue", dash=(10, 5))
rect1 = w.create_rectangle(50, 25, 150, 75, fill='yellow')

#修改坐标
w.coords(line1, 0, 25, 200, 25)
#重新配置
w.itemconfig(rect1, fill='red')
#删除
w.delete(line2)

mainloop()

Lesson 9

Convas

from tkinter import *
root = Tk()

w = Canvas(root, width=400, height=200)
w.pack()


def paint(event):
    x1, y1 = (event.x - 1), (event.y - 1)
    x2, y2 = (event.x + 1), (event.y + 1)
    w.create_oval(x1, y1, x2, y2, fill='red')


w.bind("<B1-Motion>", paint)

mainloop()

Lesson 10

from tkinter import *
root = Tk()


def callback():
    print("Moliam")


menubar = Menu(root)
menubar.add_command(label="你是?", command=callback)
menubar.add_command(label="退出", command=root.quit)
#menu和根窗口进行关联
root.config(menu=menubar)

mainloop()
from tkinter import *
root = Tk()


def callback():
    print("Moliam")


menubar = Menu(root)
#tearoff 默认为true,可分出该级菜单
filemenu = Menu(menubar, tearoff=False)
filemenu.add_command(label="打开", command=callback)
filemenu.add_command(label="保存", command=callback)
filemenu.add_separator()
filemenu.add_command(label="退出", command=root.quit)
menubar.add_cascade(label="文件", menu=filemenu)

editmenu = Menu(menubar, tearoff=False)
editmenu.add_command(label="剪切", command=callback)
editmenu.add_command(label="拷贝", command=callback)
editmenu.add_command(label="粘贴", command=callback)
menubar.add_cascade(label="编辑", menu=editmenu)

#menu和根窗口进行关联
root.config(menu=menubar)

frame = Frame(root, width=200, height=500)
frame.pack()


def popup(event):
    menubar.post(event.x_root, event.y_root)


#右键
frame.bind("<Button-3>", popup)

mainloop()

Lesson 11

事件绑定

from tkinter import *
root = Tk()


def callback(event):
    #相对于应用程序的位置
    #print("点击位置:", event.x, event.y)
    #按下的字符
    # print(event.char)
    print("当前位置:", event.x, event.y)


frame = Frame(root, width=200, height=200)
#Button 鼠标的点击事件  1代表左键  2代表滚轮  3代表右键
# frame.bind("<Button-3>", callback)
#按键  KeyPress按键按下  KeyRelease
# frame.bind("<KeyRelease>", callback)
# frame.focus_set()
#实时位置
frame.bind("<Motion>", callback)

frame.pack()

mainloop()

Lesson 12

Message

from tkinter import *

root = Tk()
#Message可自动换行
w1 = Message(root, text='我比较短', width=100)
w1.pack()
w1 = Message(root, text='我很长很长长长长长长长长长长长长', width=100)
w1.pack()

mainloop()

Lesson 13

pack

按照添加顺序排列组件

grid

按行/列形式排列组件

place

允许成程序员指定组件的大小和位置

Lesson 14

提示框

from tkinter import *
from tkinter import messagebox

print(messagebox.askokcancel("Moliam space", "打开网页?"))

mainloop()