Reputation: 1182
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:
w_frame
which contains a bunch of widget.w_frame
, I want to update a particular widget.w_frame
contains a Entry widget, radio button, button and label all available with the basic or main attributes need to display it.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.
Upvotes: 0
Views: 991
Reputation: 46
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:
lable.config(bg='red')
from the Text
widget.Here's what you can do:
Text
widget, you can use:getattr
methodeval
methoddef 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
widget_name[key]=value
.Some Useful Links:
Upvotes: 1
Reputation: 46821
For your case, you can use ast.literal_eval()
to convert a JSON string to dictionary and use the dictionary in .config()
:
from ast import literal_eval
...
def update_Frame():
a = u_text_wid.get("1.0", "end-1c") # don't include ending newline
cnf = literal_eval(a) # convert JSON string to dictionary
b.config(cnf)
Example input of the JSON string:
{"fg":"yellow", "bg":"red"}
Note that you can also use json
module to convert the JSON string as well.
Upvotes: 1