At first I used lambda in one of my tkinter buttons in order to not execute a function by itself when running the code
Button = tk.Button(root, text="Press me!", width=10, height=2, bg=BuyColor, command=lambda: sample(1, 2))
It worked well, but then I had to face this problem that my Tkinter interface freezes/lags while attempting to do the function it is calling.
With that, I found out about the use of threading that makes it possible for the root.mainloop() to not freeze while the function is running.
Button = tk.Button(root, text="Press me!", width=10, height=2, bg=BuyColor, command=threading.Thread(target=sample(1, 2)).start())
Now it works, the function does not cause the mainloop() to freeze. However, I'm now experiencing the first problem I've encountered again. The functions are running without even clicking the buttons!
I've tried this but it still causes the program to freeze even though it has threading.
Button = tk.Button(root, text="Press me!", width=10, height=2, bg=BuyColor, command=lambda: threading.Thread(target=sample(1, 2)).start())
It seems like the only way to do this is to remove the () in the target=sample(), but I need to call the sample(1, 2) function with these specific variables for each time I press the button. There are other buttons that calls the sample() function but with different variables.
Is there a more efficient way to do this without having to write different functions for different buttons?
CodePudding user response:
Thanks to @acw1668 and @Frank Yellin in the comments, I was able to fix the code.
The final code for all of this to work together is:
Button = tk.Button(root, text="Press me!", width=10, height=2, bg=YourColor, command=lambda: threading.Thread(target=sample, args=(1, 2)).start())
if the function only needs one variable, it should be:
Button = tk.Button(root, text="Press me!", width=10, height=2, bg=YourColor, command=lambda: threading.Thread(target=sample, args=(1,)).start())
Without the ,
the code won't work.