【问题标题】:Why is Threading using the class as an arg?为什么线程使用类作为参数?
【发布时间】: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


【解决方案1】:

Function 是一个方法,所以调用 self.function 隐式提供 self 作为第一个参数。如果这不是您的预期行为,请考虑切换到静态方法或使用函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多