我正在尝试为包含按钮的刽子手游戏编写代码。我正在练习课程,所以我的代码就是这样。我正在尝试做的是以某种方式连接我的按钮来识别随机变量中的一个字母,并将其替换为我显示的下划线。到目前为止,我有这个。
from tkinter import *
import random
actors = ["NICK NOLTE", "MEL GIBSON", "PATRICK STEWART", "CHRISTIAN BALE", "ARNOLD SCHWARZENEGGER",
"MATTHEW MCCONAUGHEY", "MERYL STREEP", "JOHNNY DEPP", "ANGELINA JOLIE", "CAMERON DIAZ", "AL PACINO",
"ANDY GARCIA", "JULIA ROBERTS"]
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z"]
class MyButtons:
def __init__(self, master):
buttonsFrame = Frame(master)
buttonsFrame.grid(row=0)
x = 0
y = 0
for i in letters:
button = Button(buttonsFrame, text=i, width=5, command=self.onclick(i))
button.grid(row=x, column=y)
y += 1
if y > 3:
y = 0
x += 1
def onclick(self, k):
def click():
print (k)
return click
actor = random.choice(actors)
root = Tk()
guessFrame = Frame(root)
guessFrame.grid(row=1)
buton = MyButtons(root)
def underscores():
total = ""
for i in actor:
if i == " ":
i = " "
total += i
else:
i = "_"
total += i
return total
label = Label(guessFrame, text=underscores())
label.grid(row=0)
root.mainloop()
答案 0 :(得分:0)
所以,我立即看错的是你对按钮的命令。这是它应该是什么样子。
button = Button(buttonsFrame, text=i, width=5, command=lambda k=i: self.onclick(k)))
如果使用带括号的self.onclick(i),则需要lambda的原因是您将该函数传递给另一个函数。看看是否有效,如果没有,请告诉我。