我的Python程序有相当多的代码,所以我希望你没问题,我给你了我的问题所在的部分代码。我已经为 Tkinter 创建了一个线程,并且正在尝试访问该线程中的函数。它看起来像这样:
class GUI (threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
def run(self):
window = Tk()
window.title('GUI')
window = Canvas(window, width=400, height=200)
window.pack()
def output(lampe, status):
if status == 0:
if lampe == 21:
window.create_oval(140, 30, 160, 10, fill="#FFA6A6")
if lampe == 20:
window.create_oval(170, 30, 190, 10, fill="#FAFAAA")
GUI.output(21,0)
这是我收到的消息:
类型错误:必须使用 GUI 实例作为第一个参数调用未绑定(bind)方法 output()(改为使用 int 实例)
说实话,我不知道我必须引用第一个参数的实例是什么。
最佳答案
Instance 是 python 函数需要的对象实例,在你的例子中是“self” 阅读 dive into python 中的精彩解释。你需要理解为什么在Python的类方法中使用self。对于您的问题,请查看此代码。
class GUI (threading.Thread):
window=object
def __init__(self, num):
threading.Thread.__init__(self)
def run(self):
self.window = Tk()
self.window.title('GUI')
self.window = Canvas(self.window, width=400, height=200)
self.window.pack()
@staticmethod
def output(lampe, status):
if status == 0:
if lampe == 21:
window.create_oval(140, 30, 160, 10, fill="#FFA6A6")
if lampe == 20:
window.create_oval(170, 30, 190, 10, fill="#FAFAAA")
GUI.output(21,0)
OP的其他实现
class Gui():
def __init__(self):
window = Tk()
window.title('GUI')
self.window = Canvas(window, width=400, height=200)
self.window.pack()
def output(self,lampe, status):
if status == 0:
if lampe == 21:
self.window.create_oval(140, 30, 160, 10, fill="#FFA6A6")
if lampe == 20:
self.window.create_oval(170, 30, 190, 10, fill="#FAFAAA")
并实现这个
gui=Gui()
thread=threading.Thread(target=gui.output, args=(21,0))
thread.start()
关于python - 必须使用 y 实例作为第一个参数调用未绑定(bind)方法 x() (改为使用 int 实例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31384227/