Python 3 tkinter : Switch Button

标签 python button tkinter

我想使用以下描述创建我自己的小部件: 三个按钮标有低、中、高。 在任何时候,要么没有一个被激活,要么只有一个。 被激活的应该有凹陷的浮雕。 如果我点击一个按钮,所有其他按钮的浮雕应该升高,而激活的按钮应该下沉。 我如何在 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()

以上代码将为您提供类似于以下屏幕截图的内容。我在截图前点击了“中”按钮:

screenshot

关于Python 3 tkinter : Switch Button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49323339/

相关文章:

android - 自定义 Facebook 登录按钮

安卓:按钮点击事件

python - 使用 py2exe,如何使用 python 和 tkinter 创建可执行文件?

python - 子例程参数未从 Python 正确传递到 Fortran

python - 如何在嵌套的 python 字典中映射字符串 id、索引和值

c# - 如何修改轨道脚本以在 Unity3d 中触摸的按钮上启动

python - Tkinter 进度条挂起程序并且不继续

python - 字典每个键分为多行

python - 优化 Django 中的代码——将 ManyToMany 视为矩阵

python - Tkinter:从 Entry 小部件获取数据