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