【发布时间】:2014-02-24 14:32:06
【问题描述】:
所以,我有一个列表,其中的条目如下所示:
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's)的任意数量的标签。
我一直在尝试对这种类型的东西、变量变量等进行一些阅读,似乎大多数时候(如果不是全部)这是一个非常大的 NO-NO。有些人提倡使用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。
【问题讨论】:
-
你能发布一些你的代码吗?我认为字典将是您的最佳途径,但根据所提供的信息很难判断。
-
添加了我有的代码,但目前很粗糙。
标签: python-3.x tkinter