2016-07-24 43 views
0

我的代码:如何仅在单击按钮时才返回变量的值?

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时才返回该值,但这不起作用。

感谢您的建议!

+0

我是否正确理解这一点,您希望'file_exists'函数阻塞,直到用户按下一个按钮,然后返回更新的'select'值? –

+0

我想阻止返回值,直到用户按下三个按钮之一。你编辑了我的帖子吗?如果是这样,谢谢! – Grendel

+2

为什么你要早点调用'file_exists'函数?如果该功能需要等待发生,那基本上意味着你称它为时过早,不是吗?而不是等待按钮点击发生,您应该将一个函数连接到该按钮,以便在按下该按钮时执行它。在正确的时间调用函数要比提前调用它更容易,并且等待发生。基本上像'Button(callback = do_stuff_with_select)'。 –

回答

-1

您可以利用.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()) 
+0

嗨拉威,是的,你的建议似乎工作!感谢你和所有其他人在这里! – Grendel

+0

你不应该在循环中调用'update'。相反,你可以要求tkinter阻塞,直到一个变量改变值(例如:w.wait_variable(var)') –

+0

嗨,Bryan,谢谢你的建议。不幸的是,没有tkinter变量需要改变。 – Grendel

相关问题