2

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

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

我使用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()
4

1 回答 1

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()
于 2016-04-24T17:04:53.893 回答