首页 > 解决方案 > Tkinter - 使用循环创建多个复选框

问题描述

我正在尝试创建一个程序,允许用户选择任意数量的复选框并点击一个按钮以从这些复选框返回随机结果。由于我的列表基于 Smash bros Ultimate 的名单,我试图避免创建 70 多个变量只是为了放置复选框。但是,我无法弄清楚如何迭代它。为行设置的各种值只是占位符,直到我弄明白为止。我还想在顶部有一个重置按钮,允许用户自动取消选中每个框。这段代码是我到目前为止所拥有的。任何帮助将不胜感激。

#!/usr/bin/python3

from tkinter import *
window = Tk()

#window name and header
window.title("Custom Random SSBU")
lbl = Label(window, text="Select the fighters you would like to include:")
lbl.grid(column=1, row=0)

f = [] #check boxes

ft = open("Fighters.txt").readlines() #list of all the character names

fv=[0]*78 #list for tracking what boxes are checked

ff=[] #list to place final character strings

def  reset():
   for i in fv:
       fv[i]=0

rst = Button(window, text="Reset", command=reset)
rst.grid(column=0, row=3)

for y in range (0,77):
    f[y] = Checkbutton(window, text = ft[y], variable = fv[y])
    f[y].grid(column=0, row=4+y)

def done():
    for j in fv:
        if fv[j] == 1:
            ff.append(fv[j])
    result = random.choice(ff)
    r=Label(window, text=result)

d = Button(window, text="Done", command=done)
d.grid(column=0, row = 80)

window.mainloop()

标签: pythontkinter

解决方案


不幸的是,恐怕您不得不为每个复选框创建变量。

tkinter有特殊用途的变量类variable=来保存​​不同类型的值,如果你在创建像这样的小部件时指定一个实例作为选项Checkbutton,它会在用户更改它时自动设置或重置它的值,所以你的所有程序都必须做是通过调用它的get()方法来检查它的当前值。

done()以下是在循环中创建它们(并在回调函数中使用它们)所需的代码修改示例:

import random
from tkinter import *

window = Tk()

#window name and header
window.title("Custom Random SSBU")

lbl = Label(window, text="Select the fighters you would like to include:")
lbl.grid(column=1, row=0)

with open("Fighters.txt") as fighters:
    ft = fighters.read().splitlines() # List of all the character names.

fv = [BooleanVar(value=False) for _ in ft] # List to track which boxes are checked.

ff = [] # List to place final character strings.

def  reset():
   for var in fv:
       var.set(False)

rst = Button(window, text="Reset", command=reset)
rst.grid(column=0, row=3)

for i, (name, var) in enumerate(zip(ft, fv)):
    chk_btn = Checkbutton(window, text=name, variable=var)
    chk_btn.grid(column=0, row=i+4, sticky=W)

def done():
    global ff
    ff = [name for name, var in zip(ft, fv) if var.get()]  # List of checked names.
    # Randomly select one of them.
    choice.configure(text=random.choice(ff) if ff else "None")

d = Button(window, text="Done", command=done)
d.grid(column=0, row=len(ft)+4)

choice = Label(window, text="None")
choice.grid(column=1, row=3)

window.mainloop()

我不确定您希望Label包含结果的位置,所以我只是将它放在Reset按钮的右侧。


推荐阅读