Szilard Szocs
Szilard Szocs

Reputation: 23

Global Tkinter Button not running while loop in python

I'm trying to make a button to run my while loop, but I'm stuck a little bit. My button works fine but, the while loop is not running. Can you help me out please? Here's my code:

import tkinter as tk

root = tk.Tk()
buttonClicked = False

def buttonClicked():
    global buttonClicked
    buttonClicked = not buttonClicked
    print(buttonClicked)

canvas = tk.Canvas(root, height=700, width=700)
canvas.pack()

startstop = tk.Button(root, text="Start\stop", bg="green", command=buttonClicked)
startstop.pack()


while buttonClicked == True:
    print("Hello")


root.mainloop()

Thank you in advance! Szilárd

Upvotes: 0

Views: 667

Answers (1)

IJ_123
IJ_123

Reputation: 507

You can't use direct while loops in tkinter as there is already a mainloop() running. That will either hang the whole window, or the window will not appear. Globals havenothing to do here.

As the loop is ran before clicking the button, it has no effect on what happens afterwards. Hence, you need to remove the while loop and add an if statement instead, and check it when the user clicks the button.

The code is as follows:

import tkinter as tk

root = tk.Tk()
buttonClicked = False

def buttonClicked():
    global buttonClicked
    buttonClicked = not buttonClicked
    print(buttonClicked)
    checkIfClicked()

canvas = tk.Canvas(root, height=700, width=700)
canvas.pack()

startstop = tk.Button(root, text="Start\stop", bg="green", command=buttonClicked)
startstop.pack()

def checkIfClicked():
    if buttonClicked == True:
        print("Hello")

checkIfClicked()

root.mainloop()

If you don't want to create an additional function checkIfClicked(), you can add the if statement directly into the buttonClicked() function.

Upvotes: 1

Related Questions