Search code examples
pythontkinterkeyboardwindowtoplevel

keyboard can't be used directily in Toplevel python


I'm using Toplevel to produce two windows. But when it opens the second window, the keyboard is not activated instantly (both windows are opened at the same time), I need to click the second window first in order to use the keyboard. I tried to use root.lift to fix it, but it doesn't work. What is the problem here?

My codes:

class practisePage1():
       def __init__(self, master):
           self.master = master
           self.master.update_idletasks()
           self.master.attributes('-fullscreen', True)  
           self.button1 = Button(self.master, text="NEXT", bg='gray77',   command=self.gotoPage3, anchor=CENTER)
           self.button1.pack()   

       def gotoPage1(self):
           self.root1 = Toplevel(self.master)
           self.instPage1 = practisePage1(self.root1)

class practisePage1():
       def __init__(self, master):
           self.master = master
           self.master.update_idletasks()
           self.master.attributes('-fullscreen', True)

           self.choiceA = master.bind('a', self.showResultEx1)  #can't be used directly, the window needs to be clicked first
           self.choiceB = master.bind('l', self.showResultEx2) #can't be used directly.


       def showResultEx1(self):
            #some codes
       def showResultEx2(self):
            #some codes

Thanks for your help!


Solution

  • It is keyboard focus problem. I add focus_set() before I bind my keyboard, it solves the problem.