python - Not able to include widgets in a Toplevel container in Tkinter -


i have code using tkinter opens 1 window, (after clicking button) opens toplevel container. i'm trying put label widget additional window, keep getting error saying "can't invoke label command: application has been destroyed."

how can keep root.tk() window open avoid error?

here's code looks like:

import tkinter tkinter import *  root = tk() root.wm_title("first window")   newwin = button(root, text="click me!", command=newwin) newwin.pack()   def newwin():     top = toplevel()     top.wm_title("second window")  praise = label(top, text="good work!") praise.grid()   root.mainloop() 

up until label try install in second window, code works. how can keep both windows , running?

the problem local variables not visible wider scopes. therefore, top reference not exist far rest of program concerned. easiest option put of window's logic function creates it.

from tkinter import *  root = tk() root.wm_title("first window")  def new_win():     top = toplevel()     top.wm_title("second window")     praise = label(top, text="good work!")     praise.grid()  new_win_button = button(root, text="click me!", command=new_win) new_win_button.pack()  root.mainloop() 

you go oo approach , save references relevant objects within application:

from tkinter import *  class app(object):     def __init__(self, parent):         self.parent = parent         parent.wm_title("first window")         self.new_win_button = button(root, text="click me!", command=self.new_win)         self.new_win_button.pack()         self.populate_button = button(root, text="populate", command=self.populate)         self.populate_button.pack()     def new_win(self):         self.top = toplevel()         self.top.wm_title("second window")     def populate(self):         self.praise = label(self.top, text="good work!")         self.praise.grid()  root = tk() app = app(root) root.mainloop() 

i've cleaned variable names don't class names (e.g. myclass vs. my_label).


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -