kasten
kasten

Reputation: 628

Generate a click event in tkinter

I am tring to unittest my tkitner GUI.

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 "!"

The method Test.returnEvent is not called by my generated click event. But it works as expected if I do a real click.

Upvotes: 2

Views: 5411

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386342

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.

Upvotes: 5

Related Questions