如何在下面的代码中一个接一个地突出显示单选按钮

时间:2019-01-07 08:27:49

标签: python tkinter

如何在下面的代码中高亮显示单选按钮?

以下代码处于正常工作状态,但我们无法自动突出显示按钮(扫描):

import tkinter as tk

root = tk.Tk()
v = tk.IntVar()
v.set(1)  # initializing the choice, i.e. a

languages = [
    ("a",1),
    ("b",2),
    ("c",3),
    ("d",4),
    ("e",5)
]

def ShowChoice():
    print(v.get())

tk.Label(root, 
         text="""Choose your favourite 
programming language:""",
         justify = tk.LEFT,
         padx = 36).pack()

for val, language in enumerate(languages):
    tk.Radiobutton(root, 
                  text=language,
                  padx = 20, 
                  variable=v, 
                  command=ShowChoice,
                  value=val).pack(anchor=tk.W)


root.mainloop()

屏幕截图:

Screenshot

1 个答案:

答案 0 :(得分:1)

将每个单选按钮存储到列表中……将其更改为

radios = []
r_config = {'padx':20, 'variable':v, 'command':ShowChoice}
for val, language in enumerate(languages):
    radios.append(tk.Radiobutton(root,  text=language,     
                  value=val,**r_config))
    radios[-1].pack(anchor=tk.W)

然后您可以稍后在更新方法中引用其配置

selected = -1
def color_tick():
    global selected # ... ewww
    radios[selected].config(bg=root.cget('bg'))
    selected = (selected+1)%len(radios)
    radios[selected].config(bg="yellow")
    # schedule a new call in 1 second
    root.after(1000,color_tick)

color_tick() # start the ticks
root.mainloop()