2017-07-24 61 views
0

我試圖在文本框實例名稱中使用變量,以便在for循環中通過它們進行隨機播放。例如,我有14個文本小部件(infoBox1到InfoBox14),我試圖從列表中填充。所以我想要做的是以下幾點:在tkinter中使用文本小部件的實例名稱中的變量

x=1 
for item in finalList: 

    self.infoBox(x).insert(END, item) 

    x += 1 

然後只是隨着x增加填充框。有人可以幫忙嗎?

+2

你的問題是「是否可能」,答案是,很可能是「是」。 – GrumpyCrouton

回答

3

你不需要名字來做這樣的事情。您可以將您的小部件放入列表中,然後訪問使用索引的小部件。

#you can create like this. Used -1 as index to access last added text widget 
text_list = [] 
for idx in range(14): 
    text_list.append(tkinter.Text(...)) 
    text_list[-1].grid(...) 

#then you can easily select whichever you want just like accessing any item from a list 

text_list[x].insert(...) 
#or directly 
for idx, item in enumerate(finalList): 
    text_list[idx].insert("end", item) 
1

可以做你正在嘗試做的事情。

我還沒遇到需要這樣做的情況。

下面是使用exec執行每個循環的命令的示例。

欲瞭解更多的exec語句可以蘆葦一些文檔here

注意:避免這種方法,並使用列表/字典方法,而不是。這個例子只是提供關於在python中如何實現的知識。

from tkinter import * 

class tester(Frame): 
    def __init__(self, parent, *args, **kwargs): 
     Frame.__init__(self, parent, *args, **kwargs)  

     self.parent = parent 
     self.ent0 = Entry(self.parent) 
     self.ent1 = Entry(self.parent) 
     self.ent2 = Entry(self.parent) 
     self.ent0.pack() 
     self.ent1.pack() 
     self.ent2.pack() 

     self.btn1 = Button(self.parent, text="Put numbers in each entry with a loop", command = self.number_loop) 
     self.btn1.pack() 

    def number_loop(self): 
     for i in range(3): 
      exec ("self.ent{}.insert(0,{})".format(i, i)) 


if __name__ == "__main__": 
    root = Tk() 
    app = tester(root) 
    root.mainloop() 
+0

當你在這裏時,你也可以用exec創建條目。 :) – Lafexlos

+0

是的。我只想解決OP正在使用的插入功能。 –

相關問題