gpt4 book ai didi

python - 创建一个带有未知数量复选框的窗口 - Python/tkinter

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:19 24 4
gpt4 key购买 nike

我正在为我的计算机科学类(class)开发一个涉及 python 和 tkinter 的项目。我正在尝试制作一款功能齐全的大富翁游戏,而且进展顺利。我终于遇到了一个我似乎无法克服的障碍。我正在尝试制作一个界面来抵押用户的属性(property),我想使用 tkinter checkbuttons 来获取用户输入,然后抵押所有已检查的属性(property)。这是我制作的类(class)的片段:

from tkinter import *

class Mortgager(Tk):
def __init__(self,coorder): # 'coorder' is a class that coordinates all of the
self.coorder = coorder # other classes together

Tk.__init__(self,className='Mortgager')
self.title('Mortgaging')

self.cbuttons = []
self.intvars = []
for prop in coorder.active_player.properties: # iterate through player's currently owned properties
if not prop.mortgaged:
self.intvars.append(IntVar(self,0))
self.cbuttons.append(Checkbutton(self,
variable=self.intvars[-1],text=prop.get_name(),
# Most recent intvar, method returns name of property

command=self.update_cash_onscreen)
#### Not sure what to do here...
self.cbuttons[-1].var = self.intvars[-1]
self.cbuttons[-1].text = prop.get_name()
i = 0
for cbutton in self.cbuttons: # Every three properties, new column
cbutton.grid(column=i//3,row=i%3,sticky=W,
padx=5,pady=5)
i += 1
# Haven't finished the rest of the class...

我的问题是这样的:如何创建任意数量的复选按钮,然后告诉“即时”单击了哪些复选按钮,更新某种显示当前数量的Label抵押,用 StringVar 或类似的东西,然后用总金额做一些事情?

提前致谢!

最佳答案

我完全不理解你的代码,但是如果你想在“ctrls”列表中创建带有标签的 N 个检查按钮,请尝试这个

# if ctrls is a list of all lables to your checkboxes
# i is the count and j is the text of label
for i,j in enumerate(ctrls): #what ever loop you want
var = IntVar()
c = Checkbutton(self.master,text=j,variable=var)
boxes.append([j.strip(),var,c])

稍后如果您想检查哪些按钮被选中

for i in boxes:
if i[1].get()==0:
#do what ever you want
i[2].destroy()

关于python - 创建一个带有未知数量复选框的窗口 - Python/tkinter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27339740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com