Search code examples
pythonpython-3.xtkinterevaluation

Adding and updating new widget in tkinter in runtime


I am trying to build a GUI creator using Python and Tkinter, but ran into a problem.

My problem is How to add\update widgets in runtime?

for example:

  • I have created the main window.
  • In that main window, I have created a frame name w_frame which contains a bunch of widget.
  • Based on my input in the Text or Entry widget beside the w_frame, I want to update a particular widget.
  • Lets say w_frame contains a Entry widget, radio button, button and label all available with the basic or main attributes need to display it.
  • Now I want to change the background color of label.
  • In short I want to write the code label_name.property_name=value or for example a_label.bg=red in the text widget and as soon as I press apply button, the widget should change.

I have searched on web, but not able to find the required solution. Also tried using How can i update a certain widget in tkinter, but that does not work depending on my input.

from tkinter import *
root=Tk()
w_frame=Frame()
w_frame.pack()
def update_Frame():
    a=u_text_wid.get("1.0",END)
    b.config(a)
    root.update()
def add_wid_in_frame():
    global a,b
    a=Button(w_frame,text='heelo')
    a.pack()
    b=Label(w_frame,text='heelo')
    b.pack()
u_text_wid=Text()
u_text_wid.pack()
button1=Button(text="add",command=add_wid_in_frame)
button1.pack()
button1=Button(text="update",command=update_Frame)
button1.pack()
root.mainloop()

this results me in an error

unknown option "-bg="red"

Note: I want to update the widget based on the property value provided by the user, so it wont be hard-code into the script.


Solution

  • You are getting the error because every thing you retrieve from Text widget is a string and you cannot directly pass an string to .config method, you need a keyword and then you can assign value which can be string.

    According to your question and the comments on the question, what i have figured out is:

    • You want to run lable.config(bg='red') from the Text widget.
    • You want to change the property of specific widget.

    Here's what you can do:

    1. To run Tkinter code form Text widget, you can use:
    • getattr method
    • eval method
    1. Just to change property of widget:
    def update_Frame():
        global bcd
        a = u_text_wid.get("1.0", "end-1c")
        b=a.split(",")
        c=[tuple(i.split("=")) if "=" in i else i for i in b]
        d=dict(i for i in c)
        for key,value in d.items():
            bcd[key]=value
    
    • We can use string to change property only in this format widget_name[key]=value.

    Some Useful Links: