Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a widget name with tkinter's nametowidget function within a Class

Tags:

python

tkinter

I'm writing a tkinter mini project within a class, and am currently trying to get the name of a button widget but I get a Traceback error every time the program I try to run the program. I was curious as to how to go about fixing the nametowidget line to get the proper name of the widget.

from tkinter import *
import tkinter.messagebox
root = Tk()
class WindowPane(Frame):
    def __init__(self,master):
        Frame.__init__(self,master)
        self.master = master
        self.WindowWidget()

    def WindowWidget(self):
        self.stringer = StringVar()
        self.button1 = Button(text = "Click me")
        self.button1.place(x=200,y=50)
        print(self.master.nametowidget(".button1"))
root.geometry("200x200")
playback = WindowPane(root)
root.mainloop()
like image 264
Felix Vaughan Avatar asked Sep 14 '25 05:09

Felix Vaughan


1 Answers

The "name" in nametowidget isn't the name of the variable used to keep a reference to the widget (ie: in this example it's not "button1"). This makes sense because you can have multiple variables all pointing to the same object - how would python know which name you want?

The name refers to the internal widget name used by the embedded tcl/tk interpreter. Normally this is computed based on the name of the parent, the widget class and an optional number. For example, the first frame you create by default will have the name .!frame, the next frame will have the name .!frame2, and so on. The first button inside the first frame will be named .!frame1.!button1, etc.

You can see the name of any widget by printing out its string representation. For example, in your code, you could do print(str(self.button1) which will show you that the name is actually .!button

You can't use anything built into tkinter to convert a string like "button1" to the actual widget. However, a variable such as self.button1 is an attribute of the current object, so you can use python's built-in getattr function to get the value of an attribute with a given name.

In your case you can use getattr(self, "button1") to get a reference to the actual widget object.

like image 157
Bryan Oakley Avatar answered Sep 15 '25 21:09

Bryan Oakley