Tkinter将函数与小部件的参数绑定

Ser*_*van 10 python tkinter

我有一个tkinter框架和一个连接到它的按钮:

from tkinter import *

def rand_func(a,b,c,effects):
    print (a+b+c)

root=Tk()
frame=Frame(root)
frame.bind("<Return>",lambda a=10, b=20, c=30: rand_func(a,b,c))
frame.pack()

button=Button(frame, text="click me", command=lambda a=1,b=2,c=3,eff=None:rand_func(a,b,c))
button.pack()

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

我希望当用户按下输入和按下按钮时完成相同的功能.遗憾的是,上面的代码在帧绑定时给出了错误.有谁知道这个问题的解决方案?

Bry*_*ley 18

当您创建绑定时bind,Tkinter会自动添加一个包含该事件信息的参数.您需要在rand_func定义或调用方式中对此进行说明.

使用该属性时包括此参数command.在每种情况下调用函数的方式或函数如何解释其参数时,必须注意考虑这个额外的参数.

这是一个lambda在绑定中使用的解决方案,仅在使用bind命令时接受额外事件,但不将其传递给最终命令.

import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.frame = tk.Frame(self)
        self.frame.pack()
        self.button = tk.Button(self.frame, text="click me",
                             command=lambda a=1, b=2, c=3: 
                                self.rand_func(a, b, c))
        self.button.pack()
        self.frame.bind("<Return>", 
                        lambda event, a=10, b=20, c=30: 
                            self.rand_func(a, b, c))
        # make sure the frame has focus so the binding will work
        self.frame.focus_set()

    def rand_func(self, a, b, c):
        print "self:", self, "a:", a, "b:", b, "c:", c
        print (a+b+c)

app = SampleApp()
app.mainloop()
Run Code Online (Sandbox Code Playgroud)

话虽这么说,绑定到框架是很正常的事情.通常情况下,框架不会具有键盘焦点,除非它具有焦点,否则绑定将永远不会触发.如果要设置全局绑定,则应绑定到"all"绑定标记(使用bind_all方法)或toplevel小部件.