2014-08-28 73 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