下面的脚本是如果我复制这样的链接:http://urlshortener.io/s/1234rIHs/?s=https%3A%2F%2Fexample.com%2Fsome_content%2F
,如果单击该按钮,它将更改为example.com/some_content/
。
from tkinter import *
from urllib import parse
from tkinter import Tk
root = Tk()
root.title("Slicer")
root.geometry('304x70')
lbl = Label(root, text="Link")
lbl.pack()
def clicked():
clip = root.clipboard_get()
clip = parse.unquote(clip)[45:]
root.clipboard_clear()
root.clipboard_append(clip)
lbl.configure(text= clip)
btn = Button(root, text="Slice", command=clicked, height = 3, width = 40)
btn.pack()
root.mainloop()
我正在尝试使此脚本在后台运行并侦听“复制”操作,然后,如果我在浏览器中复制了一些文本,它将自动对我刚刚复制的文本进行切片,而我不需要点击按钮。
我看到了布莱恩·奥克利(Bryan Oakley)在这个问题上的回答https://codereview.stackexchange.com/questions/184570/clipboard-detector-in-pythons
现在我尝试将他的代码与我的代码一起使用
from tkinter import *
from urllib import parse
from tkinter import Tk
root = Tk()
root.title("Slicer")
root.geometry('304x70')
lbl = Label(root, text="Link")
lbl.pack()
def check_clipboard(window):
clip = root.clipboard_get()
clip = parse.unquote(clip)[45:]
root.clipboard_clear()
root.clipboard_append(clip)
lbl.configure(text= clip)
def run_listener(window, interval):
check_clipboard(window)
root.after(interval, run_listener, window, interval)
run_listener(root, 500)
root.mainloop()
但是我遇到了错误:
Traceback (most recent call last):
File "C:\Users\leka.12\Desktop\lister.py", line 28, in <module>
run_listener(root, 500)
File "C:\Users\leka.12\Desktop\lister.py", line 25, in run_listener
check_clipboard(window)
File "C:\Users\leka.12\Desktop\lister.py", line 16, in check_clipboard
clip = root.clipboard_get()
File "C:\Users\leka.12\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 804, in clipboard_get
return self.tk.call(('clipboard', 'get') + self._options(kw))
_tkinter.TclError: CLIPBOARD selection doesn't exist or form "STRING" not defined
>>>
我也发现了这个tkinter error when copying contents from clipboard in Python
但这与我的脚本无关:
try:
selection = r.selection.get(selection="CLIPBOARD")
except tk.TclError:
selection = None