如何單擊 Tkinter 中的按鈕來建立新視窗
在本教程中,我們將介紹如何通過單擊 Tkinter 中的按鈕來建立和開啟新的 Tkinter 視窗。
建立一個新 Tkinter 視窗
import tkinter as tk
def createNewWindow():
newWindow = tk.Toplevel(app)
app = tk.Tk()
buttonExample = tk.Button(app,
text="Create new window",
command=createNewWindow)
buttonExample.pack()
app.mainloop()
通常我們用 tk.Tk()
來建立一個新的 Tkinter 視窗,但是如果我們已經建立了一個如上面的程式碼所示的 root
視窗,那這樣是無效的。
在這種情況下 Toplevel
是正確的實現索要功能的視窗控制元件,因為 Toplevel
視窗控制元件旨在顯示額外的 pop-up
視窗。
buttonExample = tk.Button(app,
text="Create new window",
command=createNewWindow)
它將 createNewWindow
功能繫結到按鈕。
在上面的示例中,新視窗是一個空視窗,你可以向其新增更多控制元件,就像在普通的 root
視窗中新增控制元件一樣,但是需要將父控制元件更改為新建立的 Toplevel
視窗。
import tkinter as tk
def createNewWindow():
newWindow = tk.Toplevel(app)
labelExample = tk.Label(newWindow, text = "New Window")
buttonExample = tk.Button(newWindow, text = "New Window button")
labelExample.pack()
buttonExample.pack()
app = tk.Tk()
buttonExample = tk.Button(app,
text="Create new window",
command=createNewWindow)
buttonExample.pack()
app.mainloop()
labelExample
和 buttonExample
將其父視窗控制元件設為 newWindow
而不是 app
。
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn