Thanks.  I managed to work it out.  I think the problem was twofold:

- I needed to call self.mywidget.focus_force(), because my test root wasn't getting focus
- I needed to call self.root.update() before *and* after the key events

This got it working.

Thanks for your feedback!

On 02/01/2018 04:35 PM, Bryan Oakley wrote:
You might need to also generate a <FocusIn> event and/or move the mouse over the widget with the warp option (widget.event_generate(..., warp=True), but you may need to also specify an x and y coordinate. I don't remember). I think some widgets check to see if they have focus, and will ignore keyboard events if they aren't focused. At least, I vaguely recall having done that a decade or two ago when I tried writing a tcl/tk testing harness.

On Wed, Jan 31, 2018 at 12:09 PM, alan moore <m...@alandmoore.com <mailto:m...@alandmoore.com>> wrote:

    Hi all,

    I'm attempting to write a unit test for a custom widget using
    Python unittest.  I'm trying to simulate actual keystrokes in my
    unit test.

    Following the example from the tkinter test suite, I created a
    test that is approximately this:

    from tkinter import Entry as MyWidget
    from tkinter.test.support import AbstractTkTest
    import unittest

    class TestMyWidget(AbstractTkTest, unittest.TestCase):

        def setUp(self):
            super().setUp()
            self.mywidget = self.create()
            self.mywidget.wait_visibility()

        def tearDown(self):
            super().tearDown()
            self.mywidget.destroy()

        def create(self):
            mw = MyWidget(self.root)
            mw.pack()
            return mw

        def _keystroke(self, char):
    self.mywidget.event_generate('<KeyPress-{}>'.format(char))
    self.mywidget.event_generate('<KeyRelease-{}>'.format(char))
            self.mywidget.update_idletasks()

        def test_key_entry(self):
            self._keystroke('a')
            self.assertEqual(self.mywidget.get(), 'a')

    if __name__ == '__main__':
        unittest.main()


    This doesn't work, though.  The keypresses don't register and
    create any text in the entry.  I can add text using event_generate
    inside a mainloop, but without mainloop it doesn't seem to work.


    Interestingly, I can use the same method to generate mouse events
    and they seem to be recognized.  Is there a way to make keypresses
    work without mainloop?

    _______________________________________________
    Tkinter-discuss mailing list
    Tkinter-discuss@python.org <mailto:Tkinter-discuss@python.org>
    https://mail.python.org/mailman/listinfo/tkinter-discuss
    <https://mail.python.org/mailman/listinfo/tkinter-discuss>



_______________________________________________
Tkinter-discuss mailing list
Tkinter-discuss@python.org
https://mail.python.org/mailman/listinfo/tkinter-discuss

Reply via email to