【问题标题】:Global Tkinter Button not running while loop in python全局 Tkinter 按钮在 python 中循环时未运行
【发布时间】:2021-11-19 11:45:41
【问题描述】:

我正在尝试制作一个按钮来运行我的 while 循环,但我有点卡住了。 我的按钮工作正常,但是 while 循环没有运行。你能帮帮我吗? 这是我的代码:

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

提前感谢您! 西拉德

【问题讨论】:

  • 您不能在 tkinter 中直接使用 while 循环,因为已经有一个 mainloop() 正在运行。这将挂起整个窗口,或者窗口不会出现。

标签: python-3.x tkinter


【解决方案1】:

您不能在 tkinter 中使用直接的 while 循环,因为已经有一个 mainloop() 正在运行。这将挂起整个窗口,或者窗口不会出现。 Globals 在这里无事可做。

由于循环在单击按钮之前运行,它对之后发生的事情没有影响。因此,您需要删除while 循环并添加一个if 语句,并在用户单击按钮时检查它。

代码如下:

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

如果您不想创建额外的函数checkIfClicked(),可以将if 语句直接添加到buttonClicked() 函数中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多