我最近完成了一个简单的命令行黑白棋游戏,现在正尝试为其创建一个 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/