我想使用以下描述创建我自己的小部件: 三个按钮标有低、中、高。 在任何时候,要么没有一个被激活,要么只有一个。 被激活的应该有凹陷的浮雕。 如果我点击一个按钮,所有其他按钮的浮雕应该升高,而激活的按钮应该下沉。 我如何在 tkinter python3 上实现它? 我能够通过一个按钮做到这一点: 这个函数是事先定义的:
def toggleLowDeer():
if DeerLowButton.config('relief')[-1] == 'sunken':
DeerLowButton.config(relief="raised")
else:
DeerLowButton.config(relief="sunken")
按钮是之后创建的
DeerLowButton = Button(root, text="L", width=1, relief="raised",
command=toggleLowDeer)
DeerLowButton.place(x=10, y=280)
最佳答案
tkinter Radiobutton 就是为此而设计的。关键是使用 indicatoron
选项。当该选项设置为 false 时,您会得到一个普通按钮,而不是一个小菱形或圆圈,当单选按钮被选中时它会凹陷,而当它没有被选中时会凸起。
例子
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()
以上代码将为您提供类似于以下屏幕截图的内容。我在截图前点击了“中”按钮:
关于Python 3 tkinter : Switch Button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49323339/