为什么这段有效的Tkinter代码在与少量PyWin32混合时崩溃?

2 投票
1 回答
877 浏览
提问于 2025-04-16 09:10

我正在用tkinter做一个非常简单的个人程序,但遇到了一些奇怪的问题。我把tkinter和pywin32结合在一起,因为我真的不喜欢pywin32的语法和命名方式,感觉tkinter用更少的代码能完成更多的事情。奇怪的地方在于,pywin32监控剪贴板和我的程序在tkinter中的反应之间的转换。

我的窗口和所有控件都是用tkinter处理的。pywin32负责监控剪贴板,并在剪贴板内容变化时进行访问。根据我对pywin32剪贴板监控部分的了解,只要你提供窗口的hwnd值,pywin32就能和你想要的任何东西一起工作。我已经做到了这一点,程序刚启动时是有效的,但当剪贴板内容变化时就不行了。

程序启动时,它能顺利地获取剪贴板内容并把它放到搜索框和编辑框里。当剪贴板被修改时,我想触发的事件确实被触发了……但之前正常工作的事件现在却导致程序卡住,而不是执行它应该做的事情。如果剪贴板内容变化,我可以把内容打印到控制台,但就是无法把这些数据放入tkinter的控件中。只有在剪贴板变化通知触发后,和tkinter控件互动时,程序才会卡住。

我感觉在把我使用的剪贴板监控示例代码适配到tkinter程序时,错过了一些pywin32的使用规则。tkinter似乎不喜欢产生堆栈跟踪或错误信息,我甚至不知道该从哪里开始用pdb调试。

这是代码:

#coding: utf-8
#Clipboard watching cribbed from ## {{{ http://code.activestate.com/recipes/355593/ (r1)

import pdb
from Tkinter import *
import win32clipboard
import win32api
import win32gui
import win32con
import win32clipboard


def force_unicode(object, encoding="utf-8"):
    if isinstance(object, basestring) and not isinstance(object, unicode):
        object = unicode(object, encoding)
    return object

class Application(Frame):
    def __init__(self, master=None):
        self.master = master
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

        self.hwnd = self.winfo_id()
        self.nextWnd = None
        self.first = True
        self.oldWndProc = win32gui.SetWindowLong(self.hwnd, win32con.GWL_WNDPROC, self.MyWndProc)
        try:
            self.nextWnd = win32clipboard.SetClipboardViewer(self.hwnd)
        except win32api.error:
            if win32api.GetLastError () == 0:
                # information that there is no other window in chain
                pass
            else:
                raise

        self.update_search_box()
        self.word_search()

    def word_search(self):
        #pdb.set_trace()
        term = self.searchbox.get()
        self.resultsbox.insert(END, term)

    def update_search_box(self):
        clipboardtext = ""
        if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_TEXT):
            win32clipboard.OpenClipboard()
            clipboardtext = win32clipboard.GetClipboardData()
            win32clipboard.CloseClipboard()

        if clipboardtext != "":
            self.searchbox.delete(0,END)
            clipboardtext = force_unicode(clipboardtext)
            self.searchbox.insert(0, clipboardtext)

    def createWidgets(self):
        self.button = Button(self)
        self.button["text"] = "Search"
        self.button["command"] = self.word_search

        self.searchbox = Entry(self)
        self.resultsbox = Text(self)

        #Pack everything down here for "easy" layout changes later
        self.searchbox.pack()
        self.button.pack()
        self.resultsbox.pack()

    def MyWndProc (self, hWnd, msg, wParam, lParam):
        if msg == win32con.WM_CHANGECBCHAIN:
            self.OnChangeCBChain(msg, wParam, lParam)
        elif msg == win32con.WM_DRAWCLIPBOARD:
            self.OnDrawClipboard(msg, wParam, lParam)

        # Restore the old WndProc. Notice the use of win32api
        # instead of win32gui here. This is to avoid an error due to
        # not passing a callable object.
        if msg == win32con.WM_DESTROY:
            if self.nextWnd:
               win32clipboard.ChangeClipboardChain (self.hwnd, self.nextWnd)
            else:
               win32clipboard.ChangeClipboardChain (self.hwnd, 0)

            win32api.SetWindowLong(self.hwnd, win32con.GWL_WNDPROC, self.oldWndProc)

        # Pass all messages (in this case, yours may be different) on
        # to the original WndProc
        return win32gui.CallWindowProc(self.oldWndProc, hWnd, msg, wParam, lParam)

    def OnChangeCBChain (self, msg, wParam, lParam):
        if self.nextWnd == wParam:
           # repair the chain
           self.nextWnd = lParam
        if self.nextWnd:
           # pass the message to the next window in chain
           win32api.SendMessage (self.nextWnd, msg, wParam, lParam)

    def OnDrawClipboard (self, msg, wParam, lParam):
        if self.first:
           self.first = False
        else:
            #print "changed"
            self.word_search()
            #self.word_search()

        if self.nextWnd:
           # pass the message to the next window in chain
           win32api.SendMessage(self.nextWnd, msg, wParam, lParam)


if __name__ == "__main__":
    root = Tk()
    app = Application(master=root)
    app.mainloop()
    root.destroy()

1 个回答

2

我不确定这是否有帮助,但我猜是因为你在一个win32事件处理器里面调用更新,tkinter可能不太喜欢这样。

通常的解决办法是通过一个after_idle()的回调来延迟更新。

所以你可以试着把:

   def OnDrawClipboard (self, msg, wParam, lParam):
    if self.first:
       self.first = False
    else:
        #print "changed"
        self.word_search()
        #self.word_search()

    if self.nextWnd:
       # pass the message to the next window in chain
       win32api.SendMessage(self.nextWnd, msg, wParam, lParam)

换成这个:

   def OnDrawClipboard (self, msg, wParam, lParam):
    if self.first:
       self.first = False
    else:
        #print "changed"
        self.after_idle(self.word_search)
        #self.word_search()

    if self.nextWnd:
       # pass the message to the next window in chain
       win32api.SendMessage(self.nextWnd, msg, wParam, lParam)

撰写回答