Here’s a version of your code with a number of changes. It fixes the TypeError
and gets rid of the card_dict
. Its not really needed anyway because that number assigned to each card can easily be stored by adding an attribute to the Button
widget representing the card. Doing this also means you only have to pass the card to the WrongOrRight()
function.
All important changes have been indicated with # ALL CAPS COMMENTS
. I also made cosmetic changes to the code so it followed the PEP 8 – Style Guide for Python Code in an effort to make it more readable and I strongly suggest that you read and follow the guidelines in the future yourself.
from tkinter import *
from tkinter import messagebox
import time
import random
difficulty = 16
rowsize= 4
columnsize = 4
numcount = 0
lastnum = 0
gotitcorrect = False
root = Tk()
root.title("MEMORY GAME!!")
root.configure(bg='gray')
def GameStart():
menuFrame.pack_forget()
gameFrame.pack()
def Timer(tim):
time.sleep(tim)
def GetRandomNumber():
lst1 = [i for i in range(1,9)]
lst2 = [i for i in range(1,9)]
random.shuffle(lst1), random.shuffle(lst2)
numlst = lst1+lst2
return numlst
def WrongOrRight(card): # REMOVED NO LONGER NEEDED SECOND ARGUMENT.
global lastnum, numcount, gotitcorrect # ADDED
number = card.number # ADDED
if numcount == 0:
lastnum = number
numcount += 1
card.configure(text=str(number))
elif numcount == 1:
if number == lastnum:
gotitcorrect = True
card.configure(text=str(number))
else:
gotitcorrect = False
card.configure(text='')
numcount -= 1
menuFrame = Frame(root, bg='gray')
menu = [Label(menuFrame, text='MEMORY GAME', bg='gray'),
Button(menuFrame, command=GameStart, text='Start', bg='gray')]
for i in menu:
i.pack()
menuFrame.pack()
numlst = GetRandomNumber()
print(numlst)
gameFrame = Frame(root, bg='gray')
cards = [[Button(gameFrame) for j in range(4)] for i in range(4)]
index = 1
#card_dict = {} # NOT NEEDED
for x in range(rowsize):
for y in range(columnsize):
print(index)
cards[x][y].grid(row=y, column=x, padx=20, pady=20)
cards[x][y].configure(text=str(numlst[index-1]))
# ADDED DEFAULT ARGUMENTS TO LAMBDA FUNCTION TO MAKE IT WORK PROPERLY
cards[x][y].configure(command=lambda x=x, y=y: WrongOrRight(cards[x][y]))
cards[x][y].number = numlst[index-1] # ADD ATTRIBUTE TO BUTTON WIDGET
# card_dict[cards[x][y]] = numlst[index-1] # NOT NEEDED
index += 1
#Timer(5) # DISABLED FOR TESTING
for x in range(rowsize):
for y in range(columnsize):
cards[x][y].configure(text='')
root.grid_rowconfigure(0,weight=1)
root.grid_columnconfigure(0,weight=1)
root.grid_rowconfigure(rowsize,weight=1)
root.grid_columnconfigure(columnsize,weight=1)
root.mainloop()
CLICK HERE to find out more related problems solutions.