You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中用Tkinter与PIL开发Blackjack游戏时如何显示卡牌图片?

Tkinter中显示卡牌图片的解决方案

你的代码存在三个核心问题,对应解决方法如下:

  • 修复路径解析错误:Windows系统路径中的反斜杠\是Python的转义字符,直接使用会导致路径解析失败。可以通过三种方式修正:

    • 使用原始字符串:r"C:\Desktop\GUI\Images\Cards\2_of_clubs.png"
    • 替换为双反斜杠:"C:\\Desktop\\GUI\\Images\\Cards\\2_of_clubs.png"
    • 改用正斜杠:"C:/Desktop/GUI/Images/Cards/2_of_clubs.png"
  • 在Canvas上绘制图片:你只创建了PhotoImage对象,但没有将其添加到Canvas组件中,需要调用canvas.create_image()方法指定图片的显示位置。

  • 保留图片引用:Tkinter的PhotoImage对象如果没有被持久引用,会被Python垃圾回收机制清理,导致图片无法显示。可以将图片对象赋值给Canvas的属性(如canvas.img = img)或者全局变量来保留引用。

修正后的完整代码:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()
root.title("Blackjack")
canvas = Canvas(root, bg="green", height=1200, width=800)
canvas.pack(fill=BOTH, expand=1)

# 使用原始字符串处理路径
img = ImageTk.PhotoImage(Image.open(r"C:\Desktop\GUI\Images\Cards\2_of_clubs.png"))
# 在画布中心位置绘制图片
canvas.create_image(400, 600, image=img)
# 保留图片引用
canvas.img = img

root.mainloop()

内容的提问来源于stack exchange,提问作者abcdan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:16:06