python - 如何销毁放置在 if 条件中的按钮小部件? Tkinter

标签 python tkinter

我无法很好地表达我的问题,但这里有一些背景。

我在 tkinter 中创建了一个按钮,并在 if 条件内使用了 .place(x, y) 但现在我想在满足另一个条件时销毁它。即使满足第二个条件,它也不会被破坏。请帮忙。

from tkinter import *

window = Tk()

button = Button(window, text='Button')

x = 10 
y = 10 # just imagine that y became 5 at some point

if x == 10:
    button.place(x=0, y=0)

elif y == 5:
    button.destroy() 

window.mainloop()

最佳答案

我不太确定你想在这里完成什么,但你似乎误解了 if-elif-else 的工作原理。它的目的是为同一变量的值提供替代方案,或者在任何情况下,两种可能性都不应该同时发生以获得所需的结果。 Elif 是“else if”的缩写,意味着仅当“if”语句为 false 时才计算它。

在您的例子中,x 已经等于 10 并且您在任何时候都不会更改它,因此始终满足“if”条件,并且代码永远不会到达“elif”语句。

如果y不断变化,达到5,可以将“elif”语句改为“if”,并在创建按钮时添加y必须不等于5的条件(否则,它会不断地创建和销毁自己)。

此外,当您当前的代码运行时,没有循环运行。该代码仅计算一次。

如果我明白你想做什么,那就是这样的。

from tkinter import *
window = Tk()
x = IntVar()
y = IntVar()

x.set(10)
y.set(10)

button = Button(window, text='Button', command=lambda: y.set(5))


def loop_this():

    if (x.get() == 10) and (y.get() != 5):
        button.place(x=0, y=0)

    if y.get() == 5:
        button.destroy()

    window.after(1000, loop_this)


loop_this()

window.mainloop()

一般来说,在使用 Tkinter 时最好使用 Tkinter 变量(IntVar、StringVar、BoolVar)。为了复制 y = 5 的场景,我在按下按钮时将其设置为等于 5,但它可以在代码中的其他位置进行更改,并且将以相同的方式工作。 主要的事情是将其放入一个函数中,将其附加到主窗口并循环运行它。为此,我们使用 .after(time_in_miliseconds_ Between_loops, function_to_loop_without_brackets)

并在window.mainloop()之前调用该函数。 希望这能回答您的问题。

关于python - 如何销毁放置在 if 条件中的按钮小部件? Tkinter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71935332/

相关文章:

python - Django ModuleNotFoundError : No module named 'sql_server' With Docker

python - 如何为 tkinter 框架添加阴影?

Python GUI 在窗口中滚动浏览照片

python - 将按键发送到嵌入式 Pygame

Python IMAP 搜索部分主题

python - 无法使用鼠兔连接到远程rabbitmq服务器

python - 如何对日期时间索引数据框进行排序

python - 类型错误 : can only concatenate tuple (not "list") to tuple"

python - 在 Python 中以编程方式在 Web 浏览器中打开 URL

Python Tkinter - 由函数创建的对象的名称