0

I am working on a project that uses XML to create a Tkinter GUI and need to know how to convert an object name to a string. For example:

# In the actual program, the value of widget variables is set by the values of XML attributes

label_name = "mylabel"

root = Tk()

exec(label_name+" = Label("+str(root)+", text='Hello World')")

Using str(root) does not work. What can I do to make this work?

Dair
  • 15,910
  • 9
  • 62
  • 107
Captain Cucumber
  • 123
  • 1
  • 3
  • 9

1 Answers1

1

Just use the string root:

exec(label_name + " = Label(root, text='Hello World')")

Demo:

In [31]: root = tkinter.Tk()
In [32]: from tkinter import Label
In [33]: exec("label_name = Label(root, text='Hello World')")
In [34]: print(label_name.grid_size())
(0, 0)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321