James Machin James Machin - 3 months ago 8
Python Question

How to reassign object to a variable in python?

If I assign a variable (in this case b) to a button and put it on screen with pack(), then later reassign b to another data type, how do I access that button so that it can be deleted or otherwise referred to? I guess the question could be asked about any data type or object, but this is case stands out because the button is left on the screen. Example:

import tkinter as tk

root=tk.Tk()
root.geometry('300x300')

b=tk.Button(root, text="button b")
b.pack()
b=1

root.mainloop()

Answer

... then later reassign b to another data type, how do I access that button so that it can be deleted or otherwise referred to?

Short answer: you can't. In order to refer to something you must keep a reference. That being said,tkinter provides some alternatives.

If you're wanting to refer to the button in the callback, you can pass it in. This requires creating the button and then defining the callback in a separate step:

b = tk.Button(...)
b.configure(command=lambda button=b: do_something)
...
def do_something(button):
    print("the widget is:", button)

Also, if you're using bindings, when the bound function is called it will be passed an event object that has an attribute that contains a reference to the widget.

b.bind("<1>", do_something)
...
def do_something(event):
    print("the widget is:", event.widget)

Finally, you can ask tkinter for a list of child widgets (eg: root.winfo_children), and if you know whether you've used pack, place or grid, you can use the slaves method to query all of the widgets being managed inside a particular container (eg: root.grid_slaves(), root.pack_slaves(), root.place_slaves())

Comments