Tkinter 如 何 使 3 张 图 片 循 环 显 示
from tkinter import *
root=Tk()
a=PhotoImage(file="d://1//1.png")
b=PhotoImage(file="d://1//2.png")
c=PhotoImage(file="d://1//3.png")
m=
n=Button(root,image=a)
n.pack()
i=0
def g():
global i
n.config(image=m)
i+=1
root.after(2000,g)
mainloop() 你的问题在于:
1. m 变量未赋值。
2. after 只执行一次,不会循环。
3. 没有切换图片的逻辑。
下面是一个完整的例子,可以让 3 张图片每隔 2 秒循环显示在同一个按钮上:
from tkinter import *
root = Tk()
# 加载图片(请确保路径正确)
a = PhotoImage(file="d://1//1.png")
b = PhotoImage(file="d://1//2.png")
c = PhotoImage(file="d://1//3.png")
# 把图片放入列表
images =
index = 0
# 创建按钮,初始显示第一张图
btn = Button(root, image=images)
btn.pack()
def switch_image():
global index
index = (index + 1) % 3 # 循环索引 0→1→2→0
btn.config(image=images)# 更换图片
root.after(2000, switch_image) # 2 秒后再次执行自身
# 启动第一次调度(2 秒后开始切换)
root.after(2000, switch_image)
root.mainloop()
要点说明:
- images 列表存放三张图片对象。
- index 记录当前显示的是第几张。
- switch_image 函数中,每调用一次就将 index 加 1,并用 % 3 取余保证只在 0、1、2 之间循环。
- 然后通过 btn.config(image=images) 更新按钮的图片。
- 最后用 root.after(2000, switch_image) 让该函数 2 秒后再执行一次,从而实现无限循环。
你原来的 after 只调用了一次,现在改为在函数内部递归调用即可。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页:
[1]