简体   繁体   中英

How to return the value of a variable only when a button has been clicked?

My code:

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

I know using nonlocal is evil but I have to go on with my procedural approach, at least for this program.

The problem is when I call this function it rushes through and returns the initial value of select (which is 0) immediately, no matter which button I've pressed. When I press a button, the value of select will change accordingly.

So how can I return it only after a button has been pressed? As you can see, my first attempt was to return the value only when select is != 0 but this doesn't work.

Thanks for your suggestions!

You can make use of the .update() function to block without freezing the GUI. Basically you call root.update() in a loop until a condition is fulfilled. An example:

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM