我正在尝试让Entry
字段在新页面打开时获得焦点:
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()
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()
class contactQues(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
entry = Entry(self)
entry.focus_force()
entry.pack()
app = DIS()
app.mainloop()
如果我移动Entry
下的startPage
字段,则焦点设置正确 - 每当我将其移至contactQues
时,它就会失去焦点。可能是Toplevel问题?
答案 0 :(得分:3)
似乎tkraise()
弄乱了焦点。因此,您需要在将页面提升到视图后调用它。我更新你的框架,总是在tkraise之后调用一些方法:
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()
如果您想避免使用不需要的postupdate()
方法,可以在尝试运行之前检查它是否存在于类中。像这样:
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
try:
frame.postupdate()
except AttributeError:
pass