所以,我有一個列表的條目任意數量的看起來像這樣:Tkinter的:創建按鈕/部件
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.
你可以發佈一些你的代碼?我認爲字典將成爲你的最佳路線,但很難告訴給出的信息。 – atlasologist
添加了我擁有的代碼,但目前非常粗糙。 – Sajber