簡體   English   中英

tkinter將單選按鈕鏈接到多個標簽並更改顏色

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

我想創建類似圖像的內容,因此,每次單擊單選按鈕時,其上方的列將變為藍色。

我需要有關如何開始在python上使用tkinter的指導

到目前為止,這是我的代碼:

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()

我才剛剛起步,我不知道自己在做什么。

編程不僅僅是在工作正常之前就扔代碼,您需要停下來思考一下如何構造數據,以便程序易於編寫和閱讀。

在您的情況下,您需要將一個按鈕鏈接到一系列小部件,這些小部件在選擇該按鈕時需要更改。 實現此目的的一種方法是使用字典,字典中包含代表按鈕值的鍵,以及代表與該單選按鈕關聯的標簽列表的值。 請注意,這不是唯一的解決方案,它只是更簡單,更明顯的解決方案之一。

例如,創建完所有小部件后,您可能會得到一個如下所示的字典:

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

這樣,您可以獲取radioVar.get()按鈕的值(例如: radioVar.get() ),然后使用該值來獲取需要更改的標簽列表:

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

您可以單獨創建每個小部件,也可以很容易地循環創建它們。 如何創建它們取決於您,但是關鍵是,您可以使用數據結構(例如字典)在單選按鈕和每個單選按鈕的標簽之間創建映射。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM