python - Tkinter,调用带参数的函数

标签 python function button tkinter frame

我最近完成了一个简单的命令行黑白棋游戏,现在正尝试为其创建一个 GUI。我的想法是,我将按 8 x 8 网格中的一个框架,这将使用框架坐标调用我的 place_tile 函数(方法)。我也能够调用需要带按钮参数的函数,但在涉及框架时我遇到了问题。有没有人知道我做错了什么或者我做错了更好的方法?

有效的示例代码:

from tkinter import *

root = Tk()
def hello(word):
    print(word)

def bye(event):
    print("Bye")

background = Frame(root, height=100, width=100)
background.bind("<Button-1>", bye)
button = Button(root, text="Bye", command=lambda:hello("Hi"))
button.pack()
background.pack()
root.mainloop()

我想做的是从类似背景的框架中调用 hello 函数之类的东西,谢谢。

最佳答案

您可以对 lambda 函数使用默认参数,示例 -

def dummy(frameobj):
    pass

background = Frame(root, height=100, width=100)
background.bind("<Button-1>", bye)
button = Button(root, text="Bye", command=lambda frameobj=background:hello(frameobj))

当调用 lambda 时,它会在没有任何参数的情况下被调用,因此将使用指定的默认值。


如果您想将参数传递给 bind() 中使用的函数,那么您还需要包含由 tkinter 自动传递的 event 参数。示例 -

def bye(event, frameobj):
    print("Bye")

background = Frame(root, height=100, width=100)
background.bind("<Button-1>", lambda event, frameobh=background: bye(event,frameobj))

但您想要的只是调用 bye() 方法的 Frame 对象,您可以使用 tkinter 传递的事件变量轻松获取它 - event.widget 。示例 -

def bye(event):
    frameobj = event.widget
    print("Bye")

background = Frame(root, height=100, width=100)
background.bind("<Button-1>", bye)

关于python - Tkinter,调用带参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32539611/

相关文章:

python - 无法在 linux 上安装 python 设置工具

python - Cython 对结构的字符串成员函数表现异常

python - 如何在 MySQL Insert 语句中使用 python 变量,出现元组错误,请提出建议

javascript 对象 - 如何绑定(bind)到 "this"

javascript (html5) - 我可以禁止两个键同时触发吗?

android - 同一页面上的多个按钮 Activity - android eclipse

python - 用于说明温度的色标,Python 脚本

javascript - 通过点击超时来终止所有正在运行的 JavaScript 函数

javascript - 一个函数适用于多个对象

javascript - 1 个带有 1 个输入字段和 2 个按钮的表单;需要根据使用的按钮更改输入名称