【问题标题】:Tkinter: Wait for either of multiple buttons to be pressed and delete all buttons after thatTkinter:等待多个按钮中的任何一个被按下,然后删除所有按钮
【发布时间】:2020-08-17 10:43:34
【问题描述】:

我有一个带有两个按钮的界面。它们具有互斥的动作,并且在满足后台 for 循环中的某个条件时生成。用户应该单击其中一个按钮,然后按钮应该消失。当在后台运行 for 循环中再次满足条件时,它们可能会重新出现。你可以想到做“选择其中一个……”类型的事情的按钮。后台的for循环需要等待用户输入。因此,我在按钮上使用了wait_variable 方法。

为了建模,我写了这个 MWE:

import tkinter as tk

root = tk.Tk()

a, b = 0, 0

var = tk.IntVar()

def Aaction():
    global a
    a += 1
    var.set(var.get()+1)
    b1.destroy()
    b2.destroy()

def Baction():
    global b
    b += 1
    var.set(var.get()+1)
    b1.destroy()
    b2.destroy()

# this happens before A and B are displayed
print('some code executing')

b1 = tk.Button(root, text='A', command=Aaction)
b1.pack()

b2 = tk.Button(root, text='B', command=Baction)
b2.pack()

b1.wait_variable(var)
print('b1 finsihed waiting')
b2.wait_variable(var) # what happens to this? `b2` is deleted when `b` is clicked. so...?
print('b2 finsihed waiting') # this is never reached

# this should happen after either A or B was clicked
print('some more code executing')

root.mainloop()

这段代码不是我想要的,但它是我试图在我的代码中解决这个问题的抽象。我的问题是:你如何正确解决这个问题?

【问题讨论】:

    标签: python user-interface asynchronous button tkinter


    【解决方案1】:

    这样的东西可以吗?

    import tkinter as tk
    
    root = tk.Tk()
    
    def Aaction():
        b1.destroy()
        b2.destroy()
        do_later()
    
    def Baction():
        b1.destroy()
        b2.destroy()
        do_later()
    
    # this happens before A and B are displayed
    print('some code executing')
    
    b1 = tk.Button(root, text='A', command=Aaction)
    b1.pack()
    
    b2 = tk.Button(root, text='B', command=Baction)
    b2.pack()
    
    # this should happen after either A or B was clicked
    def do_later():
        print('some more code executing')
    
    root.mainloop()
    

    【讨论】:

    • 几乎没有。这样的事情真的没有规范的解决方案吗?
    • 并说我是这样做的:如果我每次按下 A 或 B 时都重新启动它,我应该将后台 for 循环置于什么状态,对应于“某些代码正在执行”?它将在“最后一次”调用中终止,因为 A 和 B 删除了两个列表中的差异,并且当没有差异时循环运行。但是之前的所有调用都处于什么状态?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多