0

I am trying to add a thread to tkinter button to trigger when its presses. but as soon as I run the program, the function inside the button starts automatically before I click anything.

Here is my code:

m = Main()

root = Tk()
root.geometry("500x500")
frame = Frame(root)
frame.pack()
start = Button(frame, text="Start",
               command=threading.Thread(target=m.main).start())
stop = Button(frame, text="stop", command=quit)

start.pack(pady=20)
stop.pack()

root.mainloop()
10 Rep
  • 2,217
  • 7
  • 19
  • 33
BZ2021
  • 55
  • 5
  • I found the solution in the post below: lambda was the key. https://stackoverflow.com/questions/49085244/tkinter-button-command-getting-executed-before-clicking-the-button – BZ2021 Sep 24 '20 at 17:45
  • That isn't the best solution, because you may get an error, saying that the lambda expects a parameter. Instead, just remove the parenthese. – 10 Rep Sep 24 '20 at 17:46

1 Answers1

-1

The reason why the function runs without you clicking the button is because you are adding parentheses after the function.

So you would need to change this line:

start = Button(frame, text="Start",
               command=threading.Thread(target=m.main).start())

to this:

start = Button(frame, text="Start",
               command=threading.Thread(target=m.main).start)

All you have to do is take out the parentheses, which tells python that you only run the function if the button is clicked. If you include the parentheses, python takes it as a normal function call and ignores the button completely.

Full code: as per what you gave in your question

m = Main()

root = Tk()
root.geometry("500x500")
frame = Frame(root)
frame.pack()
start = Button(frame, text="Start",
               command=threading.Thread(target=m.main).start)
stop = Button(frame, text="stop", command=quit)

start.pack(pady=20)
stop.pack()

root.mainloop()

or you could use lambda.

10 Rep
  • 2,217
  • 7
  • 19
  • 33