[英]crate memory game in python
I'm trying to make a memory game and I'm trying to figure out how to call the action hide_text
so that the parameter will be the button I clicked.我正在尝试制作一个记忆游戏,并试图弄清楚如何调用动作hide_text
以便参数成为我单击的按钮。
from tkinter import *
from random import shuffle
root = Tk()
a = list(range(1, 19))
a = list(a) + list(a)
shuffle(a)
def game():
count = 0
for i in a:
if count == 0:
posisonx = 0
posisony = 0
if count == 6:
count = 0
posisonx = 0
posisony += 1
button = Button(root,text=f' {i} ',
command=lambda: hide_text())
button.grid(row=posisony, column=posisonx)
def hide_text(s):
s.config(text='')
posisonx += 1
count += 1
game()
root.mainloop()
There are two problems to solve here.这里有两个问题需要解决。 One is that you can't reference a button until it has been created.一个是在创建按钮之前您不能引用它。 The other is correctly capturing the reference once it has.另一个是正确地捕获参考。
If you want to pass a command involving a reference to the button, you have to split the creation into two lines:如果要传递涉及对按钮的引用的命令,则必须将创建分成两行:
button = Button(root,text=f' {i} ')
button.configure(command=...)
You need to bind button
to the lambda that you create.您需要将button
绑定到您创建的 lambda。 There are a couple of ways to do this.有几种方法可以做到这一点。 If you just do command=lambda: hide_text(button)
, all the commands will point to the last button you create in the loop.如果您只是执行command=lambda: hide_text(button)
,所有命令都将指向您在循环中创建的最后一个按钮。
One trick is to use the fact that default arguments are bound when the function is created:一个技巧是利用创建函数时绑定默认参数的事实:
button.configure(command=lamda s=button: hide_text(s))
You should take def hide_text
outside the loop in this case.在这种情况下,您应该将def hide_text
放在循环之外。
Another way is to capture a closure using a nested function.另一种方法是使用嵌套函数捕获闭包。 Put this outside the loop:把它放在循环之外:
def get_hide_text(button):
def hide_text():
button.config(text='')
return hide_text
Then, in the loop, do然后,在循环中,做
button.configure(command=get_hide_text(button))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.