所以,我有一个包含如下所示条目的列表:
Option1 Placeholder1 2 Placeholder2 0
Option2 Placeholder1 4
Option3 Placeholder1 2 Placeholder2 -2 Placeholder3 6
我有一个选项列表框和一个按钮,用于创建一个包含所选选项值的新窗口。我想做的是创造n
创建此新窗口时的按钮数量,其中n
是所选选项的值的数量(即选项 1 到 3 分别为 2、1 和 3)。我希望它看起来像这样:
Option1
Placeholder1 [button1 containing value=2]
Placeholder2 [button2 containing value=0]
...如果我只是为最大数量分配一个按钮,这当然非常简单n
我知道会出现,但我想知道是否有办法更任意地做到这一点。显然,同样的问题也适用于我需要用于值名称(“PlaceholderX”)的任意数量的标签。
我一直在尝试对此类事物、变量等进行一些阅读,似乎大多数时候(如果不是全部)这是一个非常大的禁忌。有些人主张使用dictionaries
,但我真的不明白它应该如何工作(即从条目/值中命名变量dict
).
这是可以(并且应该)完成的事情,还是我最好手动创建所有按钮?
[编辑:添加代码]
from tkinter import *
import csv
root = Tk()
root.wm_title("RP")
listFrame = Frame(root, bd=5)
listFrame.grid(row=1, column=2)
listbox1 = Listbox(listFrame)
listbox1.insert(1, "Option1")
listbox1.insert(2, "Option2")
listbox1.insert(3, "Option3")
listbox1.pack()
infoFrame = Frame(root, bd=5)
infoFrame.grid(row=1, column=3)
info_message = Message(infoFrame, width=300)
info_message.pack()
# Read stats from file
stat_file = open('DiceTest.csv', 'rU')
all_stats = list(csv.reader(stat_file, delimiter=';'))
def list_selection(event):
# gets selection and info/stats for info_message
index = int(listbox1.curselection()[0])
stats = all_stats[index]
infotext = str(stats[0]) # just the name
for n in range(int((len(stats)-2)/2)): # rest of the stats
infotext += ('\n' + str(stats[n*2 + 2]) + '\t' + str(stats[n*2 + 3]))
info_message.config(text=infotext)
listbox1.bind('<ButtonRelease-1>', list_selection)
def load():
top = Toplevel()
top.geometry('300x100')
index = int(listbox1.curselection()[0])
stats = all_stats[index]
# some way to create arbitrary buttons/labels here (?)
load_button = Button(root, text='Load', command=load)
load_button.grid(row=2, column=2)
root.mainloop()
哦,每个按钮都应该具有相同的命令/功能,这会将按钮中当前的值减少 2。