由于类结构,Tkinter返回键绑定不起作用

问题描述 投票:1回答:1

我理解如何绑定键只是在一个简单的框架上,但由于我以不同的方式构建我的应用程序,我似乎无法弄清楚如何绑定返回键按下按钮或运行按钮是的功能受限制。我一直在网站上搜索其他人的类似问题,但我找不到与我类似的问题。

我已经淡化了我的其余代码并将其放在下面:

import tkinter as tk
from tkinter import *

class POS(tk.Tk):
    def __init__(self,*args,**kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        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 (ErrorPage, MainPage):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column = 0, sticky = "nsew")

        self.show_frame(MainPage)

    def show_frame(self,cont):
        frame = self.frames[cont]
        frame.tkraise() 


class MainPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        frame = tk.Frame(self)
        frame.pack(fill = BOTH)

        button = Button(frame, text = "OK", command = self.bindHello)
        button.pack(pady=5, padx=10)

        frame.bind("<Return>", self.bindHello)
        self.bind("<Return>", self.bindHello)

    def bindHello(self, event=None):
        print("HELLO1")


#Yes this doesn't do anything but I need it for the frame container as set before
class ErrorPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        frame = tk.Frame(self)
        frame.pack(fill = BOTH)

        button = Button(frame, text = "OK", command = self.bindHello)
        button.pack(pady=5, padx=10)

        frame.bind("<Return>", self.bindHello)

    def bindHello(self, event=None):
        print("HELLO2")


app = POS()
app.mainloop()

简单的按钮绑定我原本打算按如下方式工作:

from tkinter import *
master = Tk()

def callback(event=None):
    print("Hello " + entry.get())

entry = StringVar()
e = Entry(master, textvariable = entry, width = 15)
e.pack()

b = Button(master, text="OK", command = callback)
b.pack()
master.bind("<Return>", callback)

mainloop()

我只想像上面那样有一个简单的按钮绑定,但我似乎无法为我的主程序找到工作方式。我认为这是由于我构建我的应用程序的方式,但我不完全确定。

python tkinter bind
1个回答
1
投票

在您的示例上,您绑定到窗口本身。您也可以通过多种方式在另一个中执行此操作:

#1 bind to page object's direct parent, which happens to be a Toplevel-like
#self.master.bind('<Return>', self.bindHello)

#2 recursively search page object's parents, and bind when it's a Toplevel-like
#self.winfo_toplevel().bind('<Return>', self.bindHello)

#3 bind to page object's inner frame's parent's parent, which happens to be a Toplevel-like
#frame.master.master.bind('<Return>', self.bindHello)

#4 recursively search page object's inner frame's parents, and bind when it's a Toplevel-like
frame.winfo_toplevel().bind('<Return>', self.bindHello)
© www.soinside.com 2019 - 2024. All rights reserved.