Python - 未找到 Tkinter PhotoImage 图像

Python - Tkinter PhotoImage Image Not Found

我正在为二十一点游戏编写代码。所有的 .gif 都在 .py 文件目录中,直接引用时它们工作正常。但是,当我使用下面的行时,tkinter 会报告:

_tkinter.TclError: image "SixDiamonds.gif" doesn't exist

我正在尝试使用代码获取卡名并将其插入函数 deal() 中:

w.create_image(player_coords, image=card+".gif")

但是,那是它说文件不存在的时候。如果我将行更改为特定的卡片图像:

w.create_image(player_coords, image="AceSpades.gif")

例如,然后它会起作用。但是,我需要根据绘制的卡片来引用它。任何帮助将不胜感激。

from tkinter import *
import tkinter.messagebox as messagebox

money = "0"
player = []
playervalue = 0
dealer = []
dealervalue = 0
in_play = True
not_dealt = True

root = Tk()
w = Canvas(root, height=500, width=750, bg="dark green")
card_back = PhotoImage(file="card_back.gif")
AceSpades = PhotoImage(file="AceSpades.gif")
TwoSpades = PhotoImage(file="TwoSpades.gif")
ThreeSpades = PhotoImage(file="ThreeSpades.gif")
FourSpades = PhotoImage(file="FourSpades.gif")
FiveSpades = PhotoImage(file="FiveSpades.gif")
SixSpades = PhotoImage(file="SixSpades.gif")
SevenSpades = PhotoImage(file="SevenSpades.gif")
EightSpades = PhotoImage(file="EightSpades.gif")
NineSpades = PhotoImage(file="NineSpades.gif")
TenSpades = PhotoImage(file="TenSpades.gif")
JackSpades = PhotoImage(file="JackSpades.gif")
QueenSpades = PhotoImage(file="QueenSpades.gif")
KingSpades = PhotoImage(file="KingSpades.gif")
AceHearts = PhotoImage(file="AceHearts.gif")
TwoHearts = PhotoImage(file="TwoHearts.gif")
ThreeHearts = PhotoImage(file="ThreeHearts.gif")
FourHearts = PhotoImage(file="FourHearts.gif")
FiveHearts = PhotoImage(file="FiveHearts.gif")
SixHearts = PhotoImage(file="SixHearts.gif")
SevenHearts = PhotoImage(file="SevenHearts.gif")
EightHearts = PhotoImage(file="EightHearts.gif")
NineHearts = PhotoImage(file="NineHearts.gif")
TenHearts = PhotoImage(file="TenHearts.gif")
JackHearts = PhotoImage(file="JackHearts.gif")
QueenHearts = PhotoImage(file="QueenHearts.gif")
KingHearts = PhotoImage(file="KingHearts.gif")
AceClubs = PhotoImage(file="AceClubs.gif")
TwoClubs = PhotoImage(file="TwoClubs.gif")
ThreeClubs = PhotoImage(file="ThreeClubs.gif")
FourClubs = PhotoImage(file="FourClubs.gif")
FiveClubs = PhotoImage(file="FiveClubs.gif")
SixClubs = PhotoImage(file="SixClubs.gif")
SevenClubs = PhotoImage(file="SevenClubs.gif")
EightClubs = PhotoImage(file="EightClubs.gif")
NineClubs = PhotoImage(file="NineClubs.gif")
TenClubs = PhotoImage(file="TenClubs.gif")
JackClubs = PhotoImage(file="JackClubs.gif")
QueenClubs = PhotoImage(file="QueenClubs.gif")
KingClubs = PhotoImage(file="KingClubs.gif")
AceDiamonds = PhotoImage(file="AceDiamonds.gif")
TwoDiamonds = PhotoImage(file="TwoDiamonds.gif")
ThreeDiamonds = PhotoImage(file="ThreeDiamonds.gif")
FourDiamonds = PhotoImage(file="FourDiamonds.gif")
FiveDiamonds = PhotoImage(file="FiveDiamonds.gif")
SixDiamonds = PhotoImage(file="SixDiamonds.gif")
SevenDiamonds = PhotoImage(file="SevenDiamonds.gif")
EightDiamonds = PhotoImage(file="EightDiamonds.gif")
NineDiamonds = PhotoImage(file="NineDiamonds.gif")
TenDiamonds = PhotoImage(file="TenDiamonds.gif")
JackDiamonds = PhotoImage(file="JackDiamonds.gif")
QueenDiamonds = PhotoImage(file="QueenDiamonds.gif")
KingDiamonds = PhotoImage(file="KingDiamonds.gif")

player_coords = (75, 360)
player_coords2 = (175, 360)
dealer_coords = (75, 140)
dealer_coords2 = (175, 140)


def create_deck():
    createdeck = {"AceSpades": 1, "TwoSpades": 2, "ThreeSpades": 3, "FourSpades": 4, "FiveSpades": 5, "SixSpades": 6,
                  "SevenSpades": 7, "EightSpades": 8, "NineSpades": 9, "TenSpades": 10, "JackSpades": 10,
                  "QueenSpades": 10, "KingSpades": 10, "AceHearts": 1, "TwoHearts": 2, "ThreeHearts": 3,
                  "FourHearts": 4, "FiveHearts": 5, "SixHearts": 6, "SevenHearts": 7, "EightHearts": 8, "NineHearts": 9,
                  "TenHearts": 10, "JackHearts": 10, "QueenHearts": 10, "KingHearts": 10, "AceClubs": 1, "TwoClubs": 2,
                  "ThreeClubs": 3, "FourClubs": 4, "FiveClubs": 5, "SixClubs": 6, "SevenClubs": 7, "EightClubs": 8,
                  "NineClubs": 9, "TenClubs": 10, "JackClubs": 10, "QueenClubs": 10, "KingClubs": 10, "AceDiamonds": 1,
                  "TwoDiamonds": 2, "ThreeDiamonds": 3, "FourDiamonds": 4, "FiveDiamonds": 5, "SixDiamonds": 6,
                  "SevenDiamonds": 7, "EightDiamonds": 8, "NineDiamonds": 9, "TenDiamonds": 10, "JackDiamonds": 10,
                  "QueenDiamonds": 10, "KingDiamonds": 10}
    return createdeck


def deal():
    global playervalue, dealervalue, in_play, not_dealt
    if in_play and not_dealt:
        # add inital player cards
        card, value = deck.popitem()
        player.append(card)
        playervalue += value
        w.create_image(player_coords, image=card+".gif")
        card, value = deck.popitem()
        player.append(card)
        playervalue += value
        # add initial dealer cards
        card, value = deck.popitem()
        dealer.append(card)
        dealervalue += value
        w.create_image(dealer_coords, image=card_back)
        card, value = deck.popitem()
        dealer.append(card)
        dealervalue += value
        w.create_image(dealer_coords2, image=card_back)
        print("Dealer", dealer, dealervalue)
        print("Player", player, playervalue)
        not_dealt = False


def hit():
    global playervalue, dealervalue, in_play
    if in_play:
        card, value = deck.popitem()
        player.append(card)
        playervalue += value
        print("Your current hand is", player)
        print(playervalue, "\n")
        if playervalue > 21:
            messagebox.showinfo(title="Outcome", message="You bust and lose!", parent=w)
            print("The dealer had", dealervalue, dealer, "\n")


def stand():
    global dealervalue, in_play
    if in_play:
        while dealervalue < 17:
            card, value = deck.popitem()
            dealer.append(card)
            dealervalue += value
            print("Dealer deals himself a card.\n")
        if dealervalue < 18 > 20:
            print("Dealer is staying.\n")
        scoring()


def scoring():
    global in_play
    value = str("0")
    print("Dealer score:", dealervalue)
    print("Dealers hand was", dealer, "\n")
    print("Player score:", playervalue, "\n")
    if dealervalue == 21:
        value = str("Dealer has 21, you lose!")
    elif playervalue == 21:
        value = str("You have 21, you win!")
    elif dealervalue == 21 and playervalue == 21:
        value = str("Tie! No one wins.")
    elif dealervalue > 21 and playervalue > 21:
        value = str("You both bust!")
    elif playervalue < dealervalue < 21 and playervalue < 21:
        value = str("Dealer wins.")
    elif dealervalue < playervalue and dealervalue < 21 and playervalue < 21:
        value = str("You win! Dealer loses.")
    elif dealervalue > 21:
        value = str("Dealer busts, you win!")
    messagebox.showinfo(title="Outcome", message=value, parent=w, command=root.destroy)
    in_play = False


def main():
    root.title("Blackjack")
    w.pack()
    bjbutton1 = Button(root, text="Hit", highlightbackground="dark green", command=hit)
    w.create_window(40, 480, window=bjbutton1)
    bjbutton2 = Button(root, text="Stand", highlightbackground="dark green", command=stand)
    w.create_window(100, 480, window=bjbutton2)
    bjbutton3 = Button(root, text="Deal", highlightbackground="dark green", command=deal)
    w.create_window(165, 480, window=bjbutton3)
    bjbutton4 = Button(root, text="Exit", command=root.destroy, highlightbackground="dark green")
    w.create_window(715, 480, window=bjbutton4)
    w.create_text(680, 450, text="Money: " + str(money), fill="white", justify="right",
                  font=("Brush Script MT Italic", "20"))
    w.create_text(50, 25, text="Dealer: ", fill="white", justify="right", font=("Brush Script MT Italic", "20"))
    w.create_text(50, 250, text="Player: ", fill="white", justify="right", font=("Brush Script MT Italic", "20"))
    w.mainloop()


deck = create_deck()
main()

image 属性不接受文件名。它需要一个 PhotoImage class 的实例。

the_image = PhotoImage(file="AceSpades.gif")
w.create_image(player_coords, image=the_image)

很容易将所有名称保存在一个列表中,并通过几行代码遍历该列表来创建所有卡片:

cards = ("AceSpades","TwoSpades", ...)
images = {}
for cardname in cards:
    filename = cardname + ".gif"
    images[cardname] = PhotoImage(file=filename)