Python tikinter how convert string into a variable name

Thread Starter

zazas321

Joined Nov 29, 2015
668
Hey. I am making a tkinter application and I an dispalying multiple rectangles and I want to colour them based on the name I give to the function

Code:

Code:
def picking_gui():
    global device1,device2,device3,device4,device5,device6,device7,device8,device9,device10,device11,device12,device13,device14,device15,device16,device17,device18,device19,device20
    #global canvas_tk
    device1 = canvas_tk.create_rectangle(30,400,80,450,fill='red')
    device2 = canvas_tk.create_rectangle(120,400,170,450,fill='red')
    device3 = canvas_tk.create_rectangle(220,400,270,450,fill='red')
    device4 = canvas_tk.create_rectangle(320,400,370,450,fill='red')
    device5 = canvas_tk.create_rectangle(420,400,470,450,fill='red')
    device6 = canvas_tk.create_rectangle(520,400,570,450,fill='red')
    device7 = canvas_tk.create_rectangle(620,400,670,450,fill='red')
    device8 = canvas_tk.create_rectangle(720,400,770,450,fill='red')
    device9 = canvas_tk.create_rectangle(820,400,870,450,fill='red')
    device10 = canvas_tk.create_rectangle(920,400,970,450,fill='red')
    device11 = canvas_tk.create_rectangle(30,500,80,550,fill='red')
    device12 = canvas_tk.create_rectangle(120,500,170,550,fill='red')
    device13 = canvas_tk.create_rectangle(220,500,270,550,fill='red')
    device14 = canvas_tk.create_rectangle(320,500,370,550,fill='red')
    device15 = canvas_tk.create_rectangle(420,500,470,550,fill='red')
    device16 = canvas_tk.create_rectangle(520,500,570,550,fill='red')
    device17 = canvas_tk.create_rectangle(620,500,670,550,fill='red')
    device18 = canvas_tk.create_rectangle(720,500,770,550,fill='red')
    device19 = canvas_tk.create_rectangle(820,500,870,550,fill='red')
    device20 = canvas_tk.create_rectangle(920,500,970,550,fill='red')
  
def update_rectangle_color(device_name):

    print("updating rectangle colour=",device_name)
    canvas_tk.itemconfig(str(device_name),fill="green")
    print("item updated")
    time.sleep(1)
    canvas_tk.itemconfig(device1,fill="green")# THIS DOES WORK
    canvas_tk.itemconfig(device_name,fill="green")# THIS DOES NOT WORK
So I initially create the rectangles by executing function picking_gui(), then want to change to color of certain rectangles based on the input I give. For example I give string "device1" as an arugment for update_rectangle_color() function and It would update device1 rectangle. However, it does not work because I am passing a string as an argument and it does not think that its a variable. What are my options to solve this?

I want to call function like that:
update_rectangle_color("device1"):

Instead, it expects me to call function like that:
update_rectangle_color(device1)
 
Top