2016年8月17日 星期三

[Python] TKinter callback

# reference:
# http://stupidpythonideas.blogspot.tw/2013/10/why-your-gui-app-freezes.html?view=snapshot
# http://stackoverflow.com/questions/7498658/importerror-when-importing-tkinter-in-python
# nonlocal => python3
# required => sudo apt-get install python3-tk


try:
    # for Python2
    from Tkinter import *
except ImportError:
    # for Python3
    from tkinter import *

import time


def handle_click():
    win = Toplevel(root)
    win.transient()
    Label(win, text='Please wait...', font=("Helvetica", 48)).pack()

    i = 5 
    def callback():
        nonlocal i, win 
        print(i)
        i -= 1
        if not i:
            win.destroy()
        else:
            root.after(1000, callback)
    root.after(1000, callback)

root = Tk()
Button(root, text='Click me', font=("Helvetica", 48), command=handle_click).pack()
root.mainloop()
要用 python3 才能執行, 因為 nonlocal 關鍵字不適用 python2

沒有留言: