Tkinter:在主循环中调用事件 [英] Tkinter: invoke event in main loop

查看:149
本文介绍了Tkinter:在主循环中调用事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从单独的对象调用tkinter 事件

How do you invoke a tkinter event from a separate object?

我正在寻找类似wxWidgets wx.CallAfter 之类的东西。例如,如果我创建一个对象,并将我的 Tk 根实例传递给它,然后尝试从我的对象中调用该根窗口的方法,则我的应用程序将锁定

I'm looking for something like wxWidgets wx.CallAfter. For example, If I create an object, and pass to it my Tk root instance, and then try to call a method of that root window from my object, my app locks up.

我能想到的最好的方法是使用 after 方法并单独检查状态对象,但这似乎很浪费。

The best I can come up with is to use the the after method and check the status from my separate object, but that seems wasteful.

推荐答案

回答您的特定问题如何从单独的对象调用TkInter事件,请使用 event_generate 命令。它允许您将事件注入到根窗口的事件队列中。结合Tk强大的虚拟事件机制,它成为方便的消息传递机制。

To answer your specific question of "How do you invoke a TkInter event from a separate object", use the event_generate command. It allows you to inject events into the event queue of the root window. Combined with Tk's powerful virtual event mechanism it becomes a handy message passing mechanism.

例如:

from tkinter import *

def doFoo(*args):
    print("Hello, world")

root = Tk()
root.bind("<<Foo>>", doFoo)

# some time later, inject the "<<Foo>>" virtual event at the
# tail of the event queue
root.event_generate("<<Foo>>", when="tail")

请注意, event_generate 调用将立即返回。目前尚不清楚这是否是您想要的。一般来说,您不希望基于事件的程序阻塞对特定事件的响应,因为它会冻结GUI

Note that the event_generate call will return immediately. It's not clear if that's what you want or not. Generally speaking you don't want an event based program to block waiting for a response to a specific event because it will freeze the GUI.

我不确定这是否可以解决您的问题;没有看到您的代码,我不确定您的真正问题是什么。例如,我可以在对象的构造函数中访问root的方法,在该对象中传递根而无需锁定应用程序。这告诉我您的代码中还有其他事情。

I'm not sure if this solves your problem though; without seeing your code I'm not sure what your real problem is. I can, for example, access methods of root in the constructor of an object where the root is passed in without the app locking up. This tells me there's something else going on in your code.

下面是从其他对象成功访问根窗口中的方法的示例:

Here's an example of successfully accessing methods on a root window from some other object:

from tkinter import *

class myClass:
    def __init__(self, root):
        print("root background is %s" % root.cget("background"))

root = Tk()
newObj = myClass(root)

这篇关于Tkinter:在主循环中调用事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆