【问题标题】:Tkinter windows not responding when using update() in a while loop在 while 循环中使用 update() 时,Tkinter 窗口没有响应
【发布时间】:2016-08-17 18:51:48
【问题描述】:

我是编程初学者。我这样做是出于爱好并提高工作效率。

我正在编写一个程序,当用户复制一行文本时,它会自动将剪贴板粘贴到 Tkinter entry

我使用while循环来检测当前剪贴板是否有变化,然后将新复制的剪贴板文本粘贴到Tkinter条目中。

当我复制新的一行文本时,GUI 会完美更新。

但是 GUI 没有响应,我无法单击 TK entry 输入我想要的内容。

仅供参考,我正在使用Python 3.5 软件。 提前致谢。

我的代码:

from tkinter import *
import pyperclip 

#initial placeholder
#----------------------
old_clipboard = ' '  
new_clipboard = ' '

#The GUI
#--------
root = Tk()

textvar = StringVar()

label1 = Label(root, text='Clipboard')
entry1 = Entry(root, textvariable=textvar)

label1.grid(row=0, sticky=E)
entry1.grid(row=0, column=1)

#while loop
#-----------
while(True): #first while loop: keep monitoring for new clipboard
    while(old_clipboard == new_clipboard): #second while loop: check if old_clipboard is equal to the new_clipboard
        new_clipboard = pyperclip.paste() #get the current clipboard 

    print('\nold clipboard pre copy: ' + old_clipboard)    

    old_clipboard = new_clipboard   #assign new_clipboard to old_clipboard 

    print('current clipboard post copy: ' + old_clipboard)      

    print('\ncontinuing the loop...')

    textvar.set(old_clipboard) #set the current clipboard to GUI entry

    root.update()   #update the GUI
root.mainloop()

【问题讨论】:

    标签: user-interface while-loop tkinter python-3.5 pyperclip


    【解决方案1】:

    您需要将 while 循环放在 def 中,然后在新线程中启动它,这样您的 gui 就不会冻结。 例如:

    import threading
    
    def clipboardcheck():
        #Your while loop stuff
    
    class clipboardthread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
        def run(self):
            clipboardcheck()
    
    clipboardthread.daemon=True #Otherwise you will have issues closing your program
    
    clipboardthread().start()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-19
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2021-04-30
      相关资源
      最近更新 更多