【发布时间】:2015-03-09 00:23:27
【问题描述】:
我正在尝试创建一个小计数器应用程序,但在尝试创建一个使计数器上升的实际按钮时似乎卡住了。
代码:
from tkinter import *
class CounterClass(Frame):
buttonFrame = Frame(height=200, width=200)
counterStatus = Label(buttonFrame, text="0")
def count_function(self):
i = int(self.counterStatus.cget("text"))
i += 1
self.counterStatus.config(text=str(i))
counter = Button(buttonFrame, text="+1", command=count_function)
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.buttonFrame.pack()
self.counterStatus.pack()
self.counter.pack()
if __name__ == "__main__":
root = Tk()
c = CounterClass(master=root)
c.mainloop()
root.destroy()
当我点击按钮时,它给了我这个错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tkinter/__init__.py", line 1533, in __call__
return self.func(*args)
TypeError: count_function() missing 1 required positional argument: 'self'
但是,当我创建一个应该做完全相同但我不使用类的模块时,它可以正常工作:
from tkinter import *
root = Tk()
def count_function():
i = int(counterStatus.cget("text"))
i += 1
counterStatus.config(text=str(i))
buttonFrame = Frame(height=200, width=200)
counterStatus = Label(buttonFrame, text="0")
counterButton = Button(buttonFrame, text="+1", command=count_function)
buttonFrame.pack()
counterStatus.pack()
counterButton.pack()
root.mainloop()
【问题讨论】:
-
您的第一个代码块中有错字。
class CounterClass(Frame):应该有 4 个空格。 SO的编辑器要求我更改6个字符,所以我无法为您进行编辑。
标签: python python-3.x tkinter