上一篇既使用win32
后來改進2.0版本 加入gui 使用的tkinter
但是每次點擊,很不方便,更新后,單純使用 tkinter ,去除掉win32(其實這個很簡單)
win32
是支持監視剪貼板的,不過過于復雜,同時還需要窗口句柄是win32
建立的,省去麻煩,直接用tkinter
,但是tkinter
過于簡單,僅僅支持剪切板內容獲取,清空,設置,等功能.于是需要寫循環來不斷獲取剪切板內容,來檢查是否改變.
但是直接不斷獲取剪切板,就進入了單純的循環,不能退出,以及cpu一直忙碌.一個目測可行的辦法是導入 threading,線程管理.但是,對于按鈕和線程,似乎比較復雜.
還好,tkinter.after()
支持掛起,解決這個問題.運行過程中,隨時可以退出quit
另外一個全局的變量 running
給循環一個起點
關鍵tkinter.after()
的應用##
#!/usr/bin/python
# -*- coding: utf-8 -*-
#@Author : BigBro
#@DateTime : 2015-11-17 16:57:30
#@Filename : weiyunsc_2.2.py
#@Description : 微云收藏 2.2 自動檢測 剪貼板
import tkinter
import urllib.parse
import os
running = False # Global flag
old_text = ' '
def getClipboardText(tk):
# win32clipboard.OpenClipboard()
# result = win32clipboard.GetClipboardData(win32con.CF_TEXT)
# win32clipboard.CloseClipboard()
result = tk.clipboard_get()
return result
def weiyunsc2_0(tk):
#input('復制網址,回車')
url=getClipboardText(tk)
#url=url.decode('utf-8') #transform bytes into str #tk下 獲取的內容直接為str,不需要轉換
url = str(url)
chrome = 'chrome.exe'
prefix = r'http://sc.qq.com/'
prefix2 =r'mp.weixin.qq.com'
if url.startswith(prefix):
url = url[17:] #strip 'http://sc.qq.com/'
url= urllib.parse.unquote(url)
url_list_str = ''.join([u if u !='&' else '^&' for u in list(url) ]) #cmd 命令行 對&是保留字,需要^來轉義
os.system("{0} {1}".format(chrome,url_list_str))
elif url.startswith(prefix2):
os.system("{0} {1}".format(chrome,url))
else:
url=''.join([u if u !='&' else '^&' for u in list(url) ])#如果u !='&'則u就是u,否則,u='^&'
os.system("{0} {1}".format(chrome,url))
def WatchClipboard(tk):#監視剪切板 返回
global old_text
text = getClipboardText(tk)
if running:
if old_text != text:
weiyunsc2_0(tk)
old_text = text
tk.after(500, lambda:WatchClipboard(tk))
def start():
"""Enable scanning by setting the global flag to True."""
global running
running = True
if __name__ == '__main__':
top = tkinter.Tk() #定義一個窗口
top.title('微云收藏2.2') #定義窗口標題
top.geometry('400x200') #定義窗體的大小,是400X200像素
func = tkinter.Button(top,text='開始',command = start)
func.pack(expand = 'yes', fill = 'both')
quit = tkinter.Button(top, text='Quit',
command=top.quit)
quit.pack(expand='yes', fill = 'both')
top.after(500, lambda:WatchClipboard(top))
tkinter.mainloop()