File tree Expand file tree Collapse file tree 2 files changed +34
-0
lines changed
Expand file tree Collapse file tree 2 files changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -279,6 +279,9 @@ def enter_notify_event(self, event):
279279 guiEvent = event , xy = self ._event_mpl_coords (event ))
280280
281281 def button_press_event (self , event , dblclick = False ):
282+ # set focus to the canvas so that it can receive keyboard events
283+ self ._tkcanvas .focus_set ()
284+
282285 num = getattr (event , 'num' , None )
283286 if sys .platform == 'darwin' : # 2 and 3 are reversed.
284287 num = {2 : 3 , 3 : 2 }.get (num , num )
@@ -473,6 +476,7 @@ def destroy(*args):
473476 Gcf .destroy (self )
474477 self .window .protocol ("WM_DELETE_WINDOW" , destroy )
475478 self .window .deiconify ()
479+ self .canvas ._tkcanvas .focus_set ()
476480 else :
477481 self .canvas .draw_idle ()
478482 if mpl .rcParams ['figure.raise_window' ]:
Original file line number Diff line number Diff line change @@ -185,3 +185,33 @@ class Toolbar(NavigationToolbar2Tk):
185185 print ("success" )
186186 Toolbar (fig .canvas , fig .canvas .manager .window ) # This should not raise.
187187 print ("success" )
188+
189+
190+ @pytest .mark .backend ('TkAgg' , skip_on_importerror = True )
191+ @_isolated_tk_test (success_count = 1 )
192+ def test_canvas_focus (): # pragma: no cover
193+ import tkinter as tk
194+ import matplotlib .pyplot as plt
195+ success = []
196+
197+ def check_focus ():
198+ tkcanvas = fig .canvas .get_tk_widget ()
199+ # Give the plot window time to appear
200+ if not tkcanvas .winfo_viewable ():
201+ tkcanvas .wait_visibility ()
202+ # Make sure the canvas has the focus, so that it's able to receive
203+ # keyboard events.
204+ if tkcanvas .focus_lastfor () == tkcanvas :
205+ success .append (True )
206+ plt .close ()
207+ root .destroy ()
208+
209+ root = tk .Tk ()
210+ fig = plt .figure ()
211+ plt .plot ([1 , 2 , 3 ])
212+ root .after (0 , plt .show )
213+ root .after (100 , check_focus )
214+ root .mainloop ()
215+
216+ if success :
217+ print ("success" )
You can’t perform that action at this time.
0 commit comments