Python Tkinter,基于IntVar的标签/条目数

时间:2014-08-28 15:55:44

标签: python tkinter label tkinter-entry

我希望有人可以帮助我。我想创建一个Tkinter应用程序,询问一个数字,然后使用该数字绘制正确数量的标签和Entrys。

这是我尝试做的基本头脑风暴(我知道这是错误的)

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 个答案:

答案 0 :(得分: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()