问题描述
我正在尝试对我的 tkitner GUI 进行单元测试.
I am tring to unittest my tkitner GUI.
因此我尝试从单独的线程生成点击事件.这是测试 Tkinter.Button 的示例:
Therefore I tried to generate click events from a separate thread.Here is an example testing the Tkinter.Button:
import unittest, threading
from Tkinter import *
class clickThread(threading.Thread):
def __init__(self, root):
threading.Thread.__init__(self)
self.root = root
def run(self):
button = filter(lambda a: isinstance(a, Button), self.root.children.values())[0]
print button
button.focus()
button.event_generate("<Button-1>")
button.event_generate("<ButtonRelease-1>")
print "clicked"
class Test(unittest.TestCase):
def testName(self):
root = Tk()
button = Button(root, command=self.returnEvent)
button.pack()
thread = clickThread(root)
thread.start()
root.mainloop()
def returnEvent(self):
print "!"
Test.returnEvent 方法不会被我生成的点击事件调用.但如果我真正点击它,它会按预期工作.
The method Test.returnEvent is not called by my generated click event. But it works as expected if I do a real click.
推荐答案
如果我没记错的话(可能自从我尝试了多年以来我可能没有)光标需要在按钮上才能触发绑定.
If I recall correctly (and I may not since its been years since I tried this) the cursor needs to be over tne button for the binding to fire.
你知道按钮的调用"方法吗?你可以用它来模拟按下按钮.
Are you aware of the "invoke" method of buttons? You can use it to simulate the pressing of the buttun.
这篇关于在 tkinter 中生成点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!