共計(jì) 788 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
在 Python 中使用 Tkinter 庫來創(chuàng)建圖形用戶界面(GUI)。
首先,需要導(dǎo)入 Tkinter 庫:
import tkinter as tk
然后,可以創(chuàng)建一個(gè)主窗口:
window = tk.Tk()
接下來,可以在主窗口中添加各種 GUI 組件,如標(biāo)簽、按鈕、文本框等。例如,可以創(chuàng)建一個(gè)標(biāo)簽:
label = tk.Label(window, text="Hello, Tkinter!")
label.pack()
其中,window 是要添加組件的窗口對象,text 是標(biāo)簽上顯示的文本,pack() 方法用于將組件放置在窗口中。
除了標(biāo)簽,還可以創(chuàng)建按鈕、文本框等其他組件。例如,創(chuàng)建一個(gè)按鈕:
button = tk.Button(window, text="Click me!")
button.pack()
可以為按鈕添加點(diǎn)擊事件的處理函數(shù),例如:
def button_click():
print("Button clicked!")
button = tk.Button(window, text="Click me!", command=button_click)
button.pack()
最后,需要進(jìn)入主循環(huán),以便顯示窗口和響應(yīng)用戶操作:
window.mainloop()
完整的示例代碼如下:
import tkinter as tk
def button_click():
print("Button clicked!")
window = tk.Tk()
label = tk.Label(window, text="Hello, Tkinter!")
label.pack()
button = tk.Button(window, text="Click me!", command=button_click)
button.pack()
window.mainloop()
這樣就可以創(chuàng)建一個(gè)簡單的 GUI 窗口,并在窗口中顯示標(biāo)簽和按鈕。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完