Search code examples
pythonmultithreadingtkinterargumentspython-3.7

Why is Threading using the class as an arg?


I am trying to use a thread to run a function with multiple arguments. Whenever I tried to execute the code, it would say I was providing 1 too many arguments for the function. In my last attempt, I used 1 less argument than the function needed, and voila it works by using the class itself as an argument. Here is my code.

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()

Here is the resulting output. Normally I would expect some kind of error from this; note that I only specified 2 arguments when the function calls for three!

thread started
<__main__.Window object at 0x000001A488CFF848>
spam
eggs

What is causing this to happen? Using python 3.7.5 in IDLE, if that is making a difference.


Solution

  • Function is a method, so call self.function implicitly provides self as a first argument. If that is not your intended behavior either consider switch to a static method or use a function.