如何单击 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