【发布时间】:2021-01-18 17:23:28
【问题描述】:
我正在尝试使用线程来运行具有多个参数的函数。每当我尝试执行代码时,它会说我为函数提供了 1 太多参数。在我的最后一次尝试中,我使用了比函数所需的 1 个 less 参数,瞧,它通过使用类本身作为参数来工作。这是我的代码。
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,如果这有所作为的话。
【问题讨论】:
-
这与
Thread无关。x的行为与其他方法中的self一样。如果您了解self在其他方法中的工作原理,那么,这完全一样。 -
在对象上调用方法时,第一个参数会自动设置为对象。
self.Function('spam', 'eggs')等价于Window.Function(self, 'spam', 'eggs')
标签: python multithreading tkinter arguments python-3.7