3 回答

TA貢獻1865條經驗 獲得超7個贊
這兩個小部件有不同的用途,應該相應地使用。
Radiobutton
允許從相互排斥的列表中選擇一個選項。Checkbutton
允許從列表中選擇任意數量的選項。
Radiobutton
像您一樣使用s 在這里是最合適的。
雖然毫無意義,但強制Checkbutton
s 表現得像Radiobutton
s 在技術上是可行的。
將Checkbutton
s 鏈接到同一個變量,但onvalue
為每個變量設置一個唯一的。
import tkinter as tk
root = tk.Tk()
variable = tk.IntVar(root)
for onvalue in range(1, 5 + 1):
checkbutton = tk.Checkbutton(
root,
onvalue=onvalue,
variable=variable,
)
checkbutton.pack()
root.mainloop()

TA貢獻1834條經驗 獲得超8個贊
復選按鈕和單選按鈕有不同的選項,因為它們做不同的事情。
實例Checkbutton
不支持value
選項。相反,它有一個onvalue
和offvalue
選項,用于指定小部件打開或關閉時的值。小部件也Checkbutton
需要有自己的獨特性。variable
如果您想限制用戶,使他們只能從多個值中選擇一個值,則Checkbutton
使用 a 是錯誤的小部件。這正是 的用途Radiobutton
。單選按鈕用于排他性選擇,復選按鈕用于多選。

TA貢獻1848條經驗 獲得超2個贊
如果您希望用戶只選擇一個復選框,則可以使用復選框。通過運行此代碼并選擇該選項,您就會明白這一點。我知道其他人已經回答了你的問題。但也許我的回答可以幫助某人。
from tkinter import *
root = Tk()
#Same variable but different values
radiobutton_variable = IntVar()
Radiobutton(root, text="Radiobutton only one", variable = radiobutton_variable, value = 1).grid(row = 0, column = 0)
Radiobutton(root, text="Radiobutton only one", variable = radiobutton_variable, value = 2).grid(row = 0, column = 1)
#Same variable but different values
checkbutton_variable = IntVar()
Checkbutton(root, text="Checkbutton only one", variable = checkbutton_variable, onvalue = 3).grid(row = 1, column = 0)
Checkbutton(root, text="Checkbutton only one", variable = checkbutton_variable, onvalue = 4).grid(row = 1, column = 1)
#Same variable, same values or no value
#Select both radio button
both_select_radiobutton_variable = IntVar()
Radiobutton(root, text="radiobutton both", variable = both_select_radiobutton_variable).grid(row = 2, column = 0)
Radiobutton(root, text="radiobutton both", variable = both_select_radiobutton_variable).grid(row = 2, column = 1)
#Same variable, same values or no value
#Select both check button
both_select_checkbutton_variable = IntVar()
Checkbutton(root, text="Checkbutton both", variable = both_select_checkbutton_variable).grid(row = 3, column = 0)
Checkbutton(root, text="Checkbutton both", variable = both_select_checkbutton_variable).grid(row = 3, column = 1)
mainloop()
添加回答
舉報