首页 > 解决方案 > 如何检查 Checkbutton 的值?

问题描述

我有几个复选框 - 使用 dict 和 for 循环创建。一切似乎都很好,直到我点击“检查”按钮。看来我不知道如何检查 Checkbutton 当前值。

import random
from tkinter import *


def rolldice(dice):
    return random.randrange(1, dice, 1)


root = Tk()
root.wm_title("Dices")
dices = [4, 6, 8, 10, 12, 20]
check_box = {item: BooleanVar() for item in Dices}


def checkDices():
    if C == True:
        rolldice(item in Dices)
    else:
        print("end")


for item in Dices:
    C = Checkbutton(root, text=item, variable=check_box[item], anchor=W, height=1, width=40)
    C.pack()

B1 = Button(root, text="Check", command=checkDices)
B1.pack()


root.mainloop()

标签: pythoncheckboxtkinter

解决方案


不是很清楚你想要什么,也许这段代码可以帮助

from tkinter import *
root = Tk()
root.wm_title("Dices")
Dices = [4, 6, 8, 10, 12, 20]
check_box = {it: BooleanVar() for it in Dices}

def checkDices():
    for item in check_box:
        print(item,check_box[item].get())

for item in Dices:
    C = Checkbutton(root, text=item, variable=check_box[item], anchor=W, height=1, width=40)
    C.pack()

B1 = Button(root, text="Check", command=checkDices)
B1.pack()

root.mainloop()

推荐阅读