如何仅在单击按钮时才返回变量的值?
问题描述:
我的代码:如何仅在单击按钮时才返回变量的值?
def file_exists(f_name):
select = 0
def skip():
nonlocal select
select = 1
err_msg.destroy()
def overwrite():
nonlocal select
select = 2
err_msg.destroy()
def rename():
global select
select = 3
err_msg.destroy()
# Determine whether already existing zip member's name is a file or a folder
if f_name[-1] == "/":
target = "folder"
else:
target = "file"
# Display a warning message if a file or folder already exists
''' Create a custom message box with three buttons: skip, overwrite and rename. Depending
on the users change the value of the variable 'select' and close the child window'''
if select != 0:
return select
我知道用非本地是邪恶的,但我必须继续我的处理方式,至少在这个节目。
问题是,当我调用这个函数时,它会立即通过并返回初始值select
(即0),无论按下哪个按钮。当我按下按钮时,select
的值将相应改变。
那么我只能在按下按钮后才能返回它?正如你所看到的,我的第一次尝试是仅当select为!= 0
时才返回该值,但这不起作用。
感谢您的建议!
答
您可以利用.update()
函数来阻止而不冻结GUI。基本上,您可以循环拨打root.update()
,直到条件满足。举例:
def block():
import Tkinter as tk
w= tk.Tk()
var= tk.IntVar()
def c1():
var.set(1)
b1= tk.Button(w, text='1', command=c1)
b1.grid()
def c2():
var.set(2)
b2= tk.Button(w, text='2', command=c2)
b2.grid()
while var.get()==0:
w.update()
w.destroy()
return var.get()
print(block())
我是否正确理解这一点,您希望'file_exists'函数阻塞,直到用户按下一个按钮,然后返回更新的'select'值? –
我想阻止返回值,直到用户按下三个按钮之一。你编辑了我的帖子吗?如果是这样,谢谢! – Grendel
为什么你要早点调用'file_exists'函数?如果该功能需要等待发生,那基本上意味着你称它为时过早,不是吗?而不是等待按钮点击发生,您应该将一个函数连接到该按钮,以便在按下该按钮时执行它。在正确的时间调用函数要比提前调用它更容易,并且等待发生。基本上像'Button(callback = do_stuff_with_select)'。 –