【问题标题】:How to run tkinter function with both a key bind and a button command?如何使用键绑定和按钮命令运行 tkinter 函数?
【发布时间】:2021-07-05 03:30:00
【问题描述】:

是否可以通过按下按钮和事件来运行功能?当我尝试通过按下按钮来运行此功能时,可以理解的是,它会给出错误

TypeError:listFiller() 缺少 1 个必需的位置参数:“事件”。

找不到类似的问题,但可能只是我缺乏编程知识。

代码:

class MyClass:

    def __init__(self, master):
        self.myButton = tk.Button(master, text='ok', command=self.listFiller)
        self.myButton.pack()

        self.myEntry = tk.Entry(master)
        self.myEntry.bind("<Return>",self.listFiller)
        self.myEntry.pack()

    def listFiller(self, event):
        data = self.myEntry.get()
        print(data)

【问题讨论】:

    标签: python function tkinter


    【解决方案1】:

    尝试为函数设置event=None,然后仅从bind 传递事件,例如:

    self.myButton = tk.Button(master, text='ok', command=self.listFiller)
    .....
    
    self.myEntry.bind("<Return>", lambda e: self.listFiller()) # Same as lambda e: self.listFiller(e)
    
    def listFiller(self, event=None):
        data = self.myEntry.get()
    

    这样,当您按下按钮时,event 将被视为None。但是当bind 被触发时(即,Enter 被击中),event 被隐式传递(即使你显式传递它也有效)为e

    因此,在您了解了其背后的工作原理之后,现在即使您删除 lambdae 仍会以 event 的形式传递,因为它是隐式发生的。

    self.myEntry.bind("<Return>",self.listFiller) # As mentioned by Lafexlos
    

    虽然请记住,当您按下 tkinter 按钮时,您不能使用来自 event 的任何属性,例如 event.keysym 或任何东西,但如果您使用 Enter 键,它会起作用。

    【讨论】:

    • 我认为bind 中不需要 lambda。你可以直接使用self.myEntry.bind("&lt;Return&gt;", self.listFiller),它应该会自动传递event参数。
    • @Lafexlos 是的,这也是真的。我想展示它背后的工作。生病添加。谢谢你提到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2021-04-14
    • 2018-06-10
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    相关资源
    最近更新 更多