我正在为我的主脑游戏制作一个GUI。如果您不了解规则,可以在Mastermind Rules找到它们。我遇到的问题是试图让按钮只在每次点击时将它们各自的颜色添加到列表ONCE(现在它正在添加该颜色4次)。我到目前为止的代码如下。任何帮助将不胜感激,并提前感谢您。
from tkinter import *
class Mastermind(Frame):
def __init__(self, master):
self.master = master
self.label = Label(master, text = "Colors:")
self.label.grid(row=0, column=0)
self.red_button = Button(root, text="red", command = lambda: self.get_guesses("red"))
self.orange_button = Button(text="orange", command = lambda: self.get_guesses("orange"))
self.yellow_button = Button(text="yellow", command = lambda: self.get_guesses("yellow"))
self.green_button = Button(text="green", command = lambda: self.get_guesses("green"))
self.blue_button = Button(text="blue", command = lambda: self.get_guesses("blue"))
self.purple_button = Button(text="purple", command = lambda: self.get_guesses("purple"))
self.red_button.grid(row=1, column=0)
self.orange_button.grid(row=2, column=0)
self.yellow_button.grid(row=3, column=0)
self.green_button.grid(row=4, column=0)
self.blue_button.grid(row=5, column=0)
self.purple_button.grid(row=6, column=0)
def get_guesses(self, color):
guessList = []
while len(guessList)<4:
if color == "red":
guess = ('red')
if color == "orange":
guess = ('orange')
if color == "yellow":
guess = ('yellow')
if color == "green":
guess = ('green')
if color == "blue":
guess = ('blue')
if color == "purple":
guess = ('purple')
guessList.append(guess)
print(guessList)
return guessList
答案 0 :(得分:0)
摆脱while
中的get_guesses
循环。这样做guessList
是一个实例变量而不是局部变量(因此将其移到__init__
方法中,并在其前面添加self.
)。
然后等待你的列表中有4个猜测,我只会在if
的末尾贴一个get_guesses
部分,其中包含特殊的附加逻辑,该逻辑应该只进行一次4猜测被记录下来。
答案 1 :(得分:0)
使用if
代替while
并使用变量self.guessList
def __init__(self, master):
self.guessList = []
def get_guesses(self, color):
if len(self.guessList) < 4:
self.guessList.append(color)
print(self.guessList)