【问题标题】:Cant break loop using button无法使用按钮打破循环
【发布时间】:2021-08-29 03:06:13
【问题描述】:

我想让窗口在关闭时重新出现,但只有在用户按下按钮时才会关闭。我尝试了很多次,但无法做到。请帮忙。

from Tkinter import *
x='y'
while x!='break':
    def something(x):
        x='break'
    root=tkinter.Tk()
    button=tkinter.Button(root, text='Break', command=lambda:something(x))
    button.pack()
    root.mainloop()
print('done')

【问题讨论】:

  • something 函数的开头添加 global x。您可能还想在该函数中添加root.destroy()
  • 不,我不能添加全局 x 命令解释器说'x 是参数和全局'
  • 然后从lambda:something(x)def something(x)中删除x
  • 哦,谢谢你几个月以来一直困扰着这个问题
  • 如果您愿意,您可以得到徽章、声誉和其他东西,另一个也可以看到您希望的解决方案,但非常感谢您。点赞是你想要的

标签: python loops tkinter button break


【解决方案1】:

当您使用x = "break" 设置x 时,您设置了局部变量,这意味着全局变量x 仍然是"y"。因此,要解决您的问题,只需确保使用x 的全局变量即可。这是一个简单的例子:

import tkinter as tk


def something():
    # Use the global variable for `loop_running`
    global loop_running
    loop_running = False
    # You might also want to add: root.destroy()

loop_running = True

while loop_running:
    root = tk.Tk()
    button = tk.Button(root, text="Break", command=something)
    button.pack()
    root.mainloop()

print("Done")

【讨论】:

    猜你喜欢
    • 2018-09-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 2013-03-08
    相关资源
    最近更新 更多