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