0

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

1
  • 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. Commented Nov 19, 2021 at 14:48

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.