tkinter单选按钮
时间: 2023-09-15 12:21:58 浏览: 118
在tkinter中,单选按钮可以通过Radiobutton组件来实现。为了实现单选的功能,确保一组中的所有按钮的variable选项都使用同一个变量,并使用value选项来指定每个按钮代表的值。你可以通过以下代码来创建并初始化单选按钮:
```python
import tkinter as tk
master = tk.Tk()
v = tk.IntVar()
v.set(2)
tk.Radiobutton(master, text="One", variable=v, value=1).pack(anchor="w")
tk.Radiobutton(master, text="Two", variable=v, value=2).pack(anchor="w")
tk.Radiobutton(master, text="Three", variable=v, value=3).pack(anchor="w")
master.mainloop()
```
如果你有很多选项需要创建单选按钮,可以使用以下方式来初始化Radiobutton组件:
```python
import tkinter as tk
master = tk.Tk()
GIRLS = [
("西施", 1),
("王昭君", 2),
("貂蝉", 3),
("杨玉环", 4)
]
v = tk.IntVar()
for girl, num in GIRLS:
b = tk.Radiobutton(master, text=girl, variable=v, value=num)
b.pack(anchor="w")
master.mainloop()
```
通过设置variable选项为同一个变量,并使用value选项来指定每个按钮的值,可以实现单选按钮的功能。当按钮被按下时,与之相关联的函数或方法将被自动执行。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Tkinter 组件详解(四):Radiobutton](https://blog.csdn.net/qq_41556318/article/details/85108309)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文