Python 3 tkinter:切换按钮

eeq*_*sri 2 python tkinter button

我想用以下描述创建我自己的小部件:有三个按钮标记为低,中,高.任何时候要么没有激活它们,要么只激活一个.被激活的那个应该有一个凹陷的浮雕.如果我点击一个按钮,应该提升所有其他按钮的浮雕,同时应该激活按钮.我如何在tkinter python3上实现这个?我能够为一个按钮执行此操作:此功能先前已定义:

def toggleLowDeer():
    if DeerLowButton.config('relief')[-1] == 'sunken':
        DeerLowButton.config(relief="raised")
    else:
        DeerLowButton.config(relief="sunken")
Run Code Online (Sandbox Code Playgroud)

之后创建按钮

DeerLowButton = Button(root, text="L", width=1, relief="raised", 
command=toggleLowDeer)
DeerLowButton.place(x=10, y=280)
Run Code Online (Sandbox Code Playgroud)

Bry*_*ley 7

tkinter Radiobutton旨在实现这一目标.关键是使用该indicatoron选项.当该选项设置为true时,您将获得一个正常的按钮,该按钮在选择单选按钮时会被凹陷,而在不选择时会被抬起.

import tkinter as tk

root = tk.Tk()

switch_frame = tk.Frame(root)
switch_frame.pack()

switch_variable = tk.StringVar(value="off")
off_button = tk.Radiobutton(switch_frame, text="Off", variable=switch_variable,
                            indicatoron=False, value="off", width=8)
low_button = tk.Radiobutton(switch_frame, text="Low", variable=switch_variable,
                            indicatoron=False, value="low", width=8)
med_button = tk.Radiobutton(switch_frame, text="Medium", variable=switch_variable,
                            indicatoron=False, value="medium", width=8)
high_button = tk.Radiobutton(switch_frame, text="High", variable=switch_variable,
                             indicatoron=False, value="high", width=8)
off_button.pack(side="left")
low_button.pack(side="left")
med_button.pack(side="left")
high_button.pack(side="left")

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

上面的代码将为您提供类似于以下屏幕截图的内容.在截取屏幕截图之前,我点击了"中"按钮:

截图