我试图使用一个线程运行一个函数与多个参数。每当我尝试执行代码时,它都会说我为函数提供了太多的参数。在我的最后一次尝试中,我使用的参数比函数所需的参数少1个,瞧,它通过使用类本身作为参数来工作。这是我的代码。
import threading
import sys
import tkinter
class Window():
'''Class to hold a tkinter window'''
def __init__(self, root):
'''Makes a button'''
button1 = tkinter.Button(root,
text = ' Print ',
command = self.Printer
)
button1.pack()
def Function(x,y,z):
'''function called by the thread'''
print(x)
print(y)
print(z)
def Printer(self):
'''function called by the button to start the thread'''
print('thread started')
x = threading.Thread(target=self.Function, args=('spam', 'eggs'))
x.daemon = True
x.start()
root = tkinter.Tk()
Screen = Window(root)
root.mainloop()
下面是结果输出。通常情况下,我认为会有一些错误;注意,当函数调用三个参数时,我只指定了2个参数!
thread started
<__main__.Window object at 0x000001A488CFF848>
spam
eggs
是什么导致这种情况发生?在IDLE中使用python 3.7.5,如果这会产生影响的话。
Function
是一个方法,所以调用self。函数隐式地提供self作为第一个参数。如果这不是你想要的行为,可以考虑切换到静态方法或使用函数。