[英]Missing 1 required positional argument: 'x'
from tkinter import *
import math
def calculate(x):
while x**2+math.sqrt(x) < 4:
x = x+0.000001
print(x)
gui = Tk()
gui.geometry("300x150")
button = Button(gui, text="Udregn", command=calculate).pack()
gui.mainloop()
我尝试使用此代码并单击按钮进行计算,但是一旦我按下按钮,它就会给我这个错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
TypeError: udregn() missing 1 required positional argument: 'x'
不使用任何参数调用Button
回调,这很有意义,因为按钮提供的唯一信息是已单击按钮。 您必须定义如下函数:
def calculate():
...
并考虑另一种方法来获取函数内部的x
值。 通常,它将来自另一个GUI组件,您可以将其作为全局值进行访问,也可以让calculate
是封装x
的对象的绑定方法。
class XContainer(object):
def __init__(self, x):
self.x = x
def calculate(self):
while self.x**2+math.sqrt(self.x) < 4:
self.x += 0.000001
print(self.x)
x = XContainer(5)
button = Button(gui, text="Udregn", command=x.calculate)
button.pack()
在这种情况下,其他一些代码将负责创建并可能修改x
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.