Tkinter图片交替左右布局显示异常(重叠)问题求助
Tkinter猫咪图片布局重叠问题修复
开发Tkinter应用时,想要实现猫咪图片左右交替、每两张垂直堆叠的布局,但实际运行时图片出现重叠,不符合预期。日志显示的坐标看似正确,但实际显示存在问题。
原代码
from PIL import Image, ImageTk import tkinter as tk import os import gettingimg2 as img img.get_titles_and_images("cats", 10) root = tk.Tk() root.title("Cat of the Day") root.geometry("400x900") images = [] y_position = 70 count = 0 def closing(): count = 1 while count < 11: os.remove("C:/Users/User/Desktop/cats/cutecat" + str(count) + ".jpg") count += 1 root.destroy() root.protocol("WM_DELETE_WINDOW", closing) for i in range(10): xcount = 10 swich = False if i == 1 or i == 3 or i == 5 or i == 7 or i == 9 : xcount = 200 image_path = f"C:/Users/User/Desktop/cats/cutecat{i + 1}.jpg" image = Image.open(image_path) max_width, max_height = 190, 140 image.thumbnail((max_width, max_height), Image.Resampling.LANCZOS) photo = ImageTk.PhotoImage(image) label = tk.Label(root, image=photo) label.place(x=xcount, y=y_position) if count == 2 or count == 4 or count == 6 or count == 8 or count == 10: y_position += 150 images.append(photo) count += 1 print("cutecat" + str(i + 1), "x =" + str(xcount), "y=" + str(y_position)) root.mainloop()
程序运行日志
cutecat1 x=10 y=70 cutecat2 x=200 y=70 cutecat3 x=10 y=220 cutecat4 x=200 y=220 cutecat5 x=10 y=370 cutecat6 x=200 y=370 cutecat7 x=10 y=520 cutecat8 x=200 y=520 cutecat9 x=10 y=670 cutecat10 x=200 y=670
显示效果


问题分析
日志里的y坐标是更新后的值,但实际place()使用的是更新前的y_position。原代码中,count的判断时机错误:当处理第3张图片时,count等于2,此时才会增加y_position,但第3张图片已经用原来的y=70完成了布局,导致和前两张重叠。
修复后的代码
from PIL import Image, ImageTk import tkinter as tk import os import gettingimg2 as img img.get_titles_and_images("cats", 10) root = tk.Tk() root.title("Cat of the Day") root.geometry("400x900") images = [] y_position = 70 def closing(): for count in range(1, 11): os.remove(f"C:/Users/User/Desktop/cats/cutecat{count}.jpg") root.destroy() root.protocol("WM_DELETE_WINDOW", closing) for i in range(10): # 简化x坐标判断:奇数索引(第2、4...张)放右侧 xcount = 200 if i % 2 == 1 else 10 image_path = f"C:/Users/User/Desktop/cats/cutecat{i + 1}.jpg" image = Image.open(image_path) max_width, max_height = 190, 140 image.thumbnail((max_width, max_height), Image.Resampling.LANCZOS) photo = ImageTk.PhotoImage(image) label = tk.Label(root, image=photo) label.place(x=xcount, y=y_position) # 每处理完两张(i为奇数时),增加y坐标 if i % 2 == 1: y_position += 150 images.append(photo) print(f"cutecat{i + 1} x={xcount} y={y_position if i%2==1 else y_position}") root.mainloop()
修改说明
- 用
i % 2 == 1替代繁琐的索引判断,简化xcount的设置逻辑。 - 调整
y_position的更新时机:每处理完第2、4...张图片(i为奇数)后,立即增加y_position,确保下一组两张图片使用新的y坐标布局。 - 删除无用的
count变量和swich变量,简化代码结构。 - 优化关闭函数的循环写法,更简洁。
内容的提问来源于stack exchange,提问作者Kilian
相关产品推荐
相关产品推荐

