为了账号安全,请及时绑定邮箱和手机立即绑定

Tkinter:提高框架时的焦点问题

Tkinter:提高框架时的焦点问题

慕斯王 2022-07-19 10:26:41
以下代码是触摸屏的 GUI(无鼠标,无键盘)。输入是触摸屏,它的响应就像鼠标点击一样。这是从一个更大的程序中剥离出来的,以显示该问题。它有 3 个根据需要升高的框架。理想情况下,我希望焦点在用户单击(指向)某个字段之前无处可去,然后键盘在机器 1 或机器 2 上的焦点字段中输入数字。这很好用,但如果用户不先“点击” " 在输入字段中,这会产生异常:AttributeError: 'machine1' object has no attribute 'insert'。如果键盘输入进入“位桶”或不可见(且未使用)的虚拟输入字段,我会很高兴,但可以接受默认情况下,当一个框架被提升时,焦点会自动放在第一个字段上。经过几个小时和网络上的研究,我一直无法找到解决方案。感谢您为我指明正确的方向。import tkinter as tkfrom tkinter import font  as tkfont  class MyApp(tk.Tk):    def __init__(self, *args, **kwargs):        tk.Tk.__init__(self, *args, **kwargs)        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")        # the container is where we stack the frames        # then the one we want visible is raised above the others        container = tk.Frame(self)        container.grid(row=0, column=0, sticky='news')        container.grid_rowconfigure(0, weight=1)        container.grid_columnconfigure(0, weight=1)        self.frames = {}        self.frames["machine1"] = machine1(parent=container, controller=self)        self.frames["machine2"] = machine2(parent=container, controller=self)        self.frames["running"] = running(parent=container, controller=self)        self.frames["machine1"].grid(row=0, column=0, sticky="nsew")        self.frames["machine2"].grid(row=0, column=0, sticky="nsew")        self.frames["running"].grid(row=0, column=0, sticky="nsew")        self.show_frame("running")    def show_frame(self, page_name):        '''Show a frame for the given page name'''        frame = self.frames[page_name]        frame.tkraise()        frame.focus_set() # this removed focus from the hidden windowclass Keypad(tk.Frame):    cells = [        ['1', '2', '3', '4', '5'],        ['6', '7', '8', '9', '0'],        ]
查看完整描述

1 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

某些东西总是有焦点,即使它只是根窗口。

在您的情况下,最简单的解决方案是验证焦点是否在条目小部件上,您可以这样做:

def append(self, text):
     widget = self.focus_get()
     if widget.winfo_class() == "Entry":
         widget.insert("insert", text)


查看完整回答
反对 回复 2022-07-19
  • 1 回答
  • 0 关注
  • 87 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号