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

如何在Tkinter弹跳窗口中添加图片?求入门级讲解

零基础Tkinter窗口添加图片入门讲解

我完全零基础,现在用别人给的代码做了个移动的Tkinter窗口,但搞不懂怎么加图片,麻烦用最通俗的入门方式讲清楚,我的代码如下:

import random
from time import sleep
from tkinter import *
x = random.randint(7,20)
y = random.randint(7,20)
h = random.randint(200,300)
w = random.randint(200,300)
class Window(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.width = w
        self.height = h
        self.velx = x
        self.vely = y
        self.pos = (250,250)
        self.geometry(f"{self.width}x{self.height}+{self.pos[0]}+{self.pos[1]}")
        self.configure(background='#29a32d')

        # 这里就是加图片的代码
        self.image = PhotoImage(file="C:\\Users\\semih\\Downloads\\_7OPS.png")
        Label(self, image=self.image).pack()

        
    def moveWin(self):
        x = self.pos[0] + self.velx
        y = self.pos[1] + self.vely
        downx, downy = x+self.width, y+self.height
        sWidth = self.winfo_screenwidth()  # 获取屏幕宽度
        sHeight = self.winfo_screenheight()  # 获取屏幕高度
        if x <= 0 or downx >= sWidth:
            self.velx = -self.velx
        if y <= 0 or downy >= sHeight:
            self.vely = -self.vely
        self.pos = (x,y)
        self.geometry(f"+{x}+{y}")
        return [x, y, downx, downy]
    
root = Window()

def move():
    root.moveWin()
    root.after(10, move)
move()
root.mainloop()

一、先搞懂你代码里加图片的逻辑(其实你已经写了,只是没明白)

  • 第一步:找到图片文件:self.image = PhotoImage(file="图片路径")
    • Tkinter天生只认PNG、GIF格式的图片,JPG/JPEG不行(要支持得装额外工具,新手先别碰)
    • 路径要写对:电脑里的路径是C:\Users\semih\Downloads\_7OPS.png,但代码里要把反斜杠写成两个\\,不然电脑会认错路径
  • 第二步:把图片放到窗口上:Label(self, image=self.image).pack()
    • Label就像个“展示框”,既能放文字也能放图片
    • .pack()是告诉电脑“把这个展示框放到窗口里,让它显示出来”

二、新手最容易踩的坑

  • 坑1:图片死活不显示
    • 先查路径:打开C:\Users\semih\Downloads文件夹,看看有没有_7OPS.png这个文件?名字有没有拼错?比如把.png写成.PNG?
    • 再查格式:是不是PNG/GIF?如果是JPG,转成PNG再试
    • 别丢了self.:一定要把图片存在self.image这种带self.的变量里,要是只写image = PhotoImage(...),代码运行后电脑会把图片“丢了”,自然显示不出来
  • 坑2:图片太大/太小,撑满窗口或缩成小点
    • 用subsample缩小:比如self.image = PhotoImage(file="路径").subsample(2,2),宽高都变成原来的1/2
    • 用zoom放大:比如self.image = PhotoImage(file="路径").zoom(2,2),宽高都变成原来的2倍

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 21:15:36