2014-08-28 75 views
0

我希望有人能幫助我做點什麼。我想製作一個Tkinter應用程序,要求輸入一個數字,然後使用該數字來繪製正確數量的Labels和Entrys。Python Tkinter,基於IntVar的標籤/條目數

這裏是我想要做的(我知道這是錯誤的)

from Tkinter import * 

root = Tk() 

numlines = IntVar() 

Label(root, text='Number Of Lines').grid(row=0, column=0) #this is to always stay 
Entry(root, textvariable=numlines).grid(row=0, column=1) #this is to stay always stay 
Button(root, text='Apply Number', command=apply).grid(row=1, column=1) 

def apply(): 
    # this part to draw as a block based in numline(if munlines 5 then draw these two widget 5 times on 5 rows) 
    Label(root, text='Line 1').grid(row=2, column=0)# this part to draw as a block based in numline(if munlines 5 then draw these two widget 5 times) 
    Entry(root, textvariable=numlines).grid(row=2, column=1) 

root.mainloop() 

回答

1

現實所有的Tkinter應用程序應該包含在類中被置於基本的頭腦風暴。另外,從任何包中使用import *也是一個好主意,因爲您可以覆蓋導入的未知值的問題。因此,下面的例子是在一個類的內部,並且應該給你一個這看起來如何的想法。我相信這是你要找的東西:

import Tkinter as Tk 

class App(Tk.Frame): 
    def __init__(self, master, *args, **kwargs): 
     Tk.Frame.__init__(self, *args, **kwargs) 

     self.existing_lines = 2 
     self.entry_lines = Tk.IntVar() 

     Tk.Label(self, text="Number Of Lines").grid(row=0, column=0) 
     Tk.Entry(self, textvariable=self.entry_lines).grid(row=0, column=1) 
     Tk.Button(self, text="Apply Number", command=self.add_rows).grid(row=1, column=1) 

    def add_rows(self): 
     for row in xrange(self.existing_lines, self.existing_lines+self.entry_lines.get()): 
      Tk.Label(self, text="Line %i" % (row-1)).grid(row=row, column=0) 
      Tk.Entry(self, textvariable=self.entry_lines).grid(row=row, column=1) 
      self.existing_lines+= 1 

if __name__ == "__main__": 
    root = Tk.Tk() 
    App(root).pack() 
    root.mainloop() 
+0

這太棒了,非常感謝,這正是我所需要的。關於導入*的點,我通常使用Tkinter作爲Tk,只是爲了小應用程序,我不打擾,但我會從現在開始這樣做。 保重 再次非常感謝您的時間和幫助,非常感謝。 – 2014-08-28 16:28:18

+0

您正在爲每個「Entry」指定相同的(IntVar)文本變量,因此您在其中一個條目中鍵入的內容都會以它們全部結束。考慮製作一個在新條目中使用的'StringVar'列表。 – fhdrsdg 2014-08-29 08:11:38

+0

@fhdrsdg這是OP在他的解釋中選擇做的。我假設他想這樣,所以你可以輸入你想要的行數,然後按回車。 – 2014-08-29 12:51:31