简体   繁体   中英

tkinter link radio button to more than one label and change color

I want to create something like this image, so each time I click the radio button, the column above it is colored blue.

I need guidance on how to get started using tkinter on python

This is my code so far:

from Tkinter import *

the_window = Tk()


def color_change():
    L1.configure(bg = "red")

v =IntVar()

R1 = Radiobutton(the_window, text="First", variable=v, value=1, command = color_change).pack()
R2 = Radiobutton(the_window, text="Second", variable=v, value=2, command = color_change).pack()
R2 = Radiobutton(the_window, text="Third", variable=v, value=3, command = color_change).pack()


L1 = Label(the_window,width = 10, height =1, relief = "groove", bg = "light grey")
L1.grid(row = 2, column = 2)
L1.pack()

L2 = Label(the_window,width = 10, height =1, relief = "groove", bg = "light grey")
L2.grid(row = 2, column = 2)
L2.pack() # going to make 10 more rectangles

the_window.mainloop()

I'm just getting started and I don't know what I'm doing.

Programming is more than just throwing code around until something works, you need to stop and think about how you are going to structure your data so that your program will be easy to write and easy to read.

In your case you need to link one button to a list of widgets which need to change when that button is selected. One way to accomplish this is by having a dictionary with keys that represent the button values, and values that are a list of the labels associated with that radiobutton. Note that this isn't the only solution, it's just one of the simpler, more obvious solutions.

For example, after creating all your widgets you could end up a dictionary that looks like this:

labels = {
    1: [L1, L2, L3],
    2: [l4, l5, l6],
    ...
}

With that, you can get the value of the radiobutton (eg: radioVar.get() ), and then use that to get the list of labels that need to be changed:

choice = radioVar.get()
for label in labels[choice]:
    label.configure(...)

You can create every widget individually, or you could pretty easily create them all in a loop. How you create them is up to you, but the point is, you can use a data structure such as a dictionary to create mappings between radiobuttons and the labels for each radiobutton.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM