Tkinter focus_set and focus_force not working as expected

后端 未结 1 909
情歌与酒
情歌与酒 2021-01-14 06:18

I am attempting to have the Entry field to have focus when a new page opens up:

import tkinter as tk
from tkinter import *
from tkinter import t         


        
相关标签:
1条回答
  • 2021-01-14 06:40

    It seems like tkraise() messes up the focus. So you need to invoke it after you've raised the page into view. I'd update you framework to always call some method after tkraise like so:

    import tkinter as tk
    from tkinter import *
    from tkinter import ttk
    
    class DIS(tk.Tk):
    
        def __init__(self, *args, **kwargs):
            tk.Tk.__init__(self, *args, **kwargs)
            tk.Tk.iconbitmap(self, default="")
            tk.Tk.wm_title(self, "program")
            container = tk.Frame(self)
            container.pack(side="top", fill="both", expand = True)
            container.grid_rowconfigure(0, weight = 1)
            container.grid_columnconfigure(0, weight = 1)
    
            self.frames = {}
    
            for F in (startPage, contactQues):
                frame = F(container, self)
                self.frames[F] = frame
                frame.grid(row = 0, column = 0, sticky = "nsew")
                self.show_frame(startPage)
    
        def show_frame(self, cont):
            frame = self.frames[cont]
            frame.tkraise()
            frame.postupdate()
    
    class startPage(tk.Frame):
        def __init__(self, parent, controller):
            tk.Frame.__init__(self, parent)
            button2 = ttk.Button(self, text = "Here's a Button",
                        command=lambda: controller.show_frame(contactQues))
            button2.pack()
    
        def postupdate(self):
            pass
    
    class contactQues(tk.Frame):
    
        def __init__(self, parent, controller):
            tk.Frame.__init__(self, parent)  
            self.controller = controller
    
            self.entry = Entry(self)
            self.entry.pack()
    
        def postupdate(self):
            self.entry.focus()
    
    app = DIS()
    app.mainloop()
    

    If you want to avoid having the postupdate() method where it's not needed, you could check to see if it exists in the class before trying to run it. Like so:

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        try:
            frame.postupdate()
        except AttributeError:
            pass
    
    0 讨论(0)
提交回复
热议问题