简体   繁体   English

tkinter将单选按钮链接到多个标签并更改颜色

[英]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 我需要有关如何开始在python上使用tkinter的指导

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: 这样,您可以获取radioVar.get()按钮的值(例如: radioVar.get() ),然后使用该值来获取需要更改的标签列表:

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. 如何创建它们取决于您,但是关键是,您可以使用数据结构(例如字典)在单选按钮和每个单选按钮的标签之间创建映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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