global name 'rank' is not defined
I'm new to Python programming and have problems with this code. rank and
suit does not work in method shuffle. My "simple" (?) Question is, why?
from Tkinter import *
from Canvas import Rectangle, CanvasText, Group, Window
from PIL import Image
import ImageTk
win = Tk()
text = Text(win, width=65, height=15, font=("Arial", 10))
win.title("Play High or Low Card")
win.geometry("700x600")
class Card(object):
RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q",
"K"]
SUIT = ["Python/projekt/bilder/hearts.png",
"Python/projekt/bilder/spades.png",
"Python/projekt/bilder/diamond.png",
"Python/projekt/bilder/clubs.png"]
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __str__(self):
rep = self.rank + self.suit
return rep
def draw(self,suit,rank):
bg = ImageTk.PhotoImage(Image.open(self.suit).resize((10, 10)))
cardGraph = Canvas(win, width=70, height=100, bg="White", bd=1,
relief='solid', highlightthickness=2)
cardGraph.photo=bg
cardGraph.create_image(10,10, image=bg, anchor=CENTER) #left/up
cardGraph.create_image(53,93, image=bg, anchor=CENTER) #right/down
cardGraph.create_text(20, 10, text=self.rank, font=("Helvetica",
8, "bold")) #left/up
cardGraph.create_text(63, 93, text=self.rank, font=("Helvetica",
8, "bold")) #right/down
cardGraph.create_text(36, 50, text=self.rank, font=("Helvetica",
12, "bold")) #middle
cardGraph.pack(side = "left", anchor=NW)
class Hand(object):
def __init__(self):
self.cards = []
def __str__ (self):
if self.cards:
rep = ""
for card in self.cards:
rep += str(card) + " "
else:
rep = "<empty>"
return rep
def clear(self):
self.cards = []
def add(self, card):
self.cards.append(card)
def give(self, card, other_hand):
self.cards.remove(card)
other_hand.add(card)
class Deck(Hand, Card):
def populate(self):
for suit in Card.SUIT:
for rank in Card.RANKS:
self.add(Card(rank, suit))
DrawCard = Card(rank,suit)
DrawCard.draw(self,rank)
def shuffle(self):
import random
random.shuffle(self.cards)
DrawCard = Card(rank,suit)
DrawCard.draw(self,rank)
def deal(self, hands, per_hand = 1):
for rounds in range(per_hand):
for hand in hands:
if self.cards:
top_card = self.cards[1]
self.give(top_card, hand)
else:
print("Cant continue deck. Out of cards!!")
deck1 = Deck()
deck1.populate()
deck1.shuffle()
my_hand = Hand()
your_hand = Hand()
hands = [my_hand, your_hand]
deck1.deal(hands, per_hand = 5)
print(my_hand)
shuffleBtn = Button(win, text="Turn", command=lambda: deck1.shuffle())
shuffleBtn.pack()
mainloop()
The traceback is:
Traceback (most recent call last): File "C:/Users/RaJ/Desktop/Cards", line
95, in deck1.shuffle() File "C:/Users/RaJ/Desktop/Cards", line 77, in
shuffle DrawCard = Card(rank,suit) NameError: global name 'rank' is not
defined
No comments:
Post a Comment