|
发表于 2021-7-20 19:54:13
|
显示全部楼层
本帖最后由 阿奇_o 于 2021-7-20 20:15 编辑
master, parent 的确是类似的意思。
就像 定义主窗口对象时,有的喜欢叫 root, 有的叫 win, window, 有的又叫 master
初学的话,可以先简单熟悉一下常用的组件,如 Label, Button, Entry,Toplevel, Canvas, Listbox 等等,
参考https://tkdocs.com/tutorial/index.html , https://realpython.com/python-gui-tkinter/
然后,直接做一个稍微复杂的,遇到问题 再Google搜具体的应用例子,如 tkinter open second window
靠前的通常是 stackoverflow.com, geeksforgeeks.com, realpython.com 等好网站
至于 tkinter的三个布局方法,一开始还是自己手工写实在,更能加强对GUI的理解。
我现在写的话,一般会这样:
- from tkinter import *
- from tkinter import ttk
- class App(Tk): # 直接继承Tk类, 方便构造 主窗口对象
- def __init__(self, geo, title):
- super().__init__()
- self.geometry(geo) # 理解:此时的 self 将是 主窗口对象,
- self.title(title)
- self.name = ''
- self.initUI() # 初始化UI
- # 初始化其他功能
- self.shortcut()
- def initUI(self):
- self.lb = Label(self, text='输入你的名字:')
- self.lb.pack(pady=10)
- self.ent = Entry(master=self, )
- self.ent.pack(pady=(10, 50))
- self.frame = Frame(master=self, width=250, height=50, background='white', )
- self.frame.pack(fill='y', expand=True)
- # self.frame.pack(fill='y', ) # 注:pack布局方法,会影响frame的实际显示大小
- self.lb = Label(master=self.frame, text='Hello', font=('Helveta', 18))
- self.lb.grid(row=0, column=0, padx=10, pady=10)
- self.bt = Button(master=self.frame, text='click获取', command=self.get_name)
- self.bt.grid(row=0, column=1, padx=10, pady=10)
- self.bt_s = Button(self, text='打开新窗口', command=self.second_win)
- self.bt_s.pack()
-
- def shortcut(self):
- self.bind("<Control-q>", lambda e: self.destroy()) # Ctrl+Q 关闭主窗口
- # self.ent.focus()
- self.ent.bind("<Return>", lambda e: self.get_name()) # 当输入框激活时,按回车,触发函数
- # 绑定名称参考:https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/key-names.html
- def get_name(self):
- self.lb['text'] = 'Hello, ' + self.ent.get()
- self.ent.delete(0, END)
- def second_win(self,):
- self.tl = Toplevel(self, bg='white')
- self.tl.geometry("1000x800")
-
- self.withdraw() # 隐藏主窗口
- # self.deiconify() # 显示主窗口
-
- win = App(geo="500x300+200+100", title='tkinter GUI OOP Basic Demo') # 构造主窗口Tk对象
- win.mainloop()
复制代码
|
|