0, if the click button, run a more time-consuming operation, then the interface will be stuck dead
ImportTkinter as TKImport Timedefonclick (text, i): Time.sleep (3) Text.insert (tk. END,'the {} button is pressed \ n'. Format (i)) root=tk. Tk () Text=tk. Text (Root) text.pack () Tk. Button (root, Text='Button 1', command=Lambda: OnClick (text,1) . Pack () Tk. Button (root, Text='Button 2', command=Lambda: OnClick (text,2) . Pack () Root.mainloop ()
Workaround:
Way one, direct thread
ImportTkinter as TKImport TimeImportthreadingsongs= ['Love Business','Friends','go home for New Year',' Good Day']movies= [' Avatar','Monkey Ball Rising']defMusic (Songs):GlobalText#intentional, note the difference from the movie forSinchSongs:text.insert (tk. END,"listen to the song:%s \t--%s\n"%(S, Time.ctime ())) Time.sleep (3)defMovie (Movies, text): forMinchMovies:text.insert (tk. END,"Watch Movie:%s \t--%s\n"%(M, Time.ctime ())) Time.sleep (5) defThread_it (func, *args):" "Package a function into a thread" " #Createt = Threading. Thread (Target=func, args=args)#Guardian!!!T.setdaemon (True)#StartT.start ()#blocking--The card-dead interface! #T.join ()Root=tk. Tk () Text=tk. Text (Root) text.pack () Tk. Button (root, Text='Music', command=Lambda: Thread_it (music, songs)). Pack () Tk. Button (root, Text='movie', command=Lambda: Thread_it (movie, movies, Text)). Pack () Root.mainloop ()
Way two, inherit threading. Thread class
ImportTkinter as TKImport TimeImportthreadingsongs= ['Love Business','Friends','go home for New Year',' Good Day']movies= [' Avatar','Monkey Ball Rising']defMusic (Songs):GlobalText#intentional, note the difference from the movie forSinchSongs:text.insert (tk. END,"listen to the song:%s \t--%s\n"%(S, Time.ctime ())) Time.sleep (3)defMovie (Movies, text): forMinchMovies:text.insert (tk. END,"Watch Movie:%s \t--%s\n"%(M, Time.ctime ())) Time.sleep (5)classMyThread (Threading. Thread):def __init__(Self, func, *args): Super ().__init__() Self.func=func Self.args=args Self.setdaemon (True) Self.start ()#to start Here defRun (self): Self.func (*Self.args) Root=tk. Tk () Text=tk. Text (Root) text.pack () Tk. Button (root, Text='Music', command=Lambda: MyThread (music, songs)). Pack () Tk. Button (root, Text='movie', command=Lambda: MyThread (movie, movies, Text)). Pack () Root.mainloop ()
Solution for Tkinter Interface card