Python的Tkinter点击按钮触发事件
如果要開發(fā)一個比較大的程序,那么應(yīng)該先把代碼封裝起來,在面向?qū)ο缶幊讨?#xff0c;就是封裝成類
先看代碼:
import tkinter as tk
class App:
? ? def __init__(self, root):
? ? ? ? root.title("打招呼測試")
? ? ? ? frame = tk.Frame(root)
? ? ? ? frame.pack()
? ? ? ? self.hi_there = tk.Button(frame, text="打招呼", fg="blue", command=self.say_hi)
? ? ? ? self.hi_there.pack(side=tk.LEFT)
? ? def say_hi(self):
? ? ? ? print("您剛才通過點(diǎn)擊打招呼觸發(fā)了我:大家好,我是badao!")
root = tk.Tk()
app = App(root)
root.mainloop()
程序跑起來后:
代碼解釋:
#導(dǎo)入tkinter模塊并創(chuàng)建別名tk
import tkinter as tk
class App:
? ? def __init__(self, root):
? ? ? ?#設(shè)置標(biāo)題
? ? ? ? root.title("打招呼測試")
? ? ? ?#創(chuàng)建一個框架,然后在里面添加一個Button組件
? ? ? ?#框架的作用一般是在復(fù)雜的布局中起到將組件分組的作用
? ? ? ? frame = tk.Frame(root)
? ? ? ? #pack()自動調(diào)節(jié)組件自身尺寸
? ? ? ? frame.pack()
?????????#創(chuàng)建一個按鈕組件,fg是foreground(前景色)
? ? ? ? self.hi_there = tk.Button(frame, text="打招呼", fg="blue", command=self.say_hi)
????? ? #左對齊
? ? ? ? self.hi_there.pack(side=tk.LEFT)
? ? ? ? print("您剛才通過點(diǎn)擊打招呼觸發(fā)了我:大家好,我是badao!")
#創(chuàng)建一個toplevel的根窗口,并把它作為參數(shù)實(shí)例化app對象
root = tk.Tk()app = App(root)
#開始主事件循環(huán)
root.mainloop()
總結(jié)
以上是生活随笔為你收集整理的Python的Tkinter点击按钮触发事件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python的GUI的最终选择Tkint
- 下一篇: python的GUI之Tkinter的L