Come creare una nuova finestra cliccando un pulsante in Tkinter
In questo tutorial vi mostreremo come creare e aprire una nuova finestra di Tkinter cliccando su un pulsante in Tkinter.
Creare una nuova finestra 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()
Normalmente usiamo tk.Tk() per creare una nuova finestra Tkinter, ma non è valida se abbiamo già creato una finestra root come mostrato nei codici precedenti.
Toplevel è il widget giusto in questa circostanza, in quanto il widget Toplevel è destinato a visualizzare finestre pop-up aggiuntive.
buttonExample = tk.Button(app, text="Create new window", command=createNewWindow)
Esso lega la funzione createNewWindow al pulsante.
La nuova finestra è una finestra vuota nell’esempio precedente e si potrebbero aggiungere altri widget, proprio come aggiungere widget in una normale finestra di root, ma è necessario cambiare il widget padre con la finestra Toplevel creata.
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()
Come si può vedere, labelExample e buttonExample hanno il loro widget padre come newWindow ma non 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 Facebook