如何使用For循环创建Tkinter按钮?

时间:2013-06-18 00:06:48

标签: python-2.7 tkinter

我正在尝试创建一个基本的Gmail客户端,但我似乎遇到了动态创建Tkinter按钮的问题。在我的班级Main_Window中,我有一个名为mainFun的方法。在这个方法中是这个代码,它试图创建11个按钮,编号为1-11。

for i in range(1,11):

    self.newmessage = Button(self, text = "%d" % i)
    Main_Window.entryFrame.append(self.newmessage)

令人讨厌的是,我在运行代码时遇到错误。

Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "copyright", "credits" or "license()" for more information.
==== No Subprocess ====
>>> 
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
    return self.func(*args)
  File "/media/PI_USB/Email Send/Email Send GUI V2.py", line 111, in remember_Authen
    self.authen_credits()
  File "/media/PI_USB/Email Send/Email Send GUI V2.py", line 101, in authen_credits
    app = Main_Window()
  File "/media/PI_USB/Email Send/Email Send GUI V2.py", line 225, in __init__
    self.mainFun()
  File "/media/PI_USB/Email Send/Email Send GUI V2.py", line 281, in mainFun
    Main_Window.entryFrame.append(self.newmessage)
AttributeError: class Main_Window has no attribute 'entryFrame'

如果需要,这里是我的代码的其余部分的pastebin链接:

http://pastebin.com/7J9newip

谢谢!

1 个答案:

答案 0 :(得分:0)

  • Main_Window.entryFrame似乎是self.entryFrame
  • 的拼写错误
  • Tkinter.Frame没有append:在框架作为父级创建窗口小部件时,要将窗口小部件附加到框架。然后拨打widget.pack(..)widget.grid(..)

for i in range(1,11):
    self.newmessage = Button(self.entryFrame, text="%d" % i)
    self.newmessage.pack()