Python Tkinter 图像撕裂滚动

问题描述 投票:0回答:0

我正在做一个项目来创建一个 GUI 应用程序,以在 Tkinter 中将图像显示为可点击的按钮。我已经完成了图像出现在 GUI 上的可滚动网格中的功能。但是,当向上或向下滚动时,图像会出现可怕的屏幕撕裂。有没有办法用 Tkinter 解决这个问题,或者这是因为 python 不是最快的语言并且图形操作有点昂贵?例如,如果我必须用 C++ 重写程序以使其更快,那很好,但我想知道在采取该步骤之前是否有必要采取这种措施。我是 GUI 应用程序的新手,所以如果我犯了一些明显的错误,请告诉我。

提前感谢您的帮助,代码如下:


import os
import json
import tkinter as tk
from tkinter import ttk
from math import *
from tkinter import *
from PIL import ImageTk, Image

directory = "IMG DIR HERE!" #<--CHANGE THIS FOR YOUR SYSTEM!
class Img: 
    def __init__(self,name=-2,img=-2):
        self.name = name
        self.img = img


def event(args):
    canvas.configure(scrollregion = canvas.bbox("all"))

def command(): 
   
    print("Hello")


def resize_img(raw_img):
    std_size = (300,300) 
    img = raw_img.resize(std_size)
    return img



def getimages(): 
   
    images = os.listdir(directory); 

    Imgs=[]
    exts = ["gif","jpg","png"]
    for name in images:
        ext = name.split(".")[1]
        print(ext)
        if ext not in exts: 
            print("False")
            continue        
        print("True")
        raw_img = Image.open(directory + "/"+name)
        img = resize_img(raw_img)
        img = ImageTk.PhotoImage(img) 
        img = Img(name,img)
        Imgs.append(img)
    
    return Imgs

root= tk.Tk()
root.geometry("1000x400")
root.title("Display Image App")


images = getimages()



#Create A Main Frame
main_frame = Frame(root)
main_frame.pack(fill=BOTH,expand=1)


#Create A Canvas
canvas = Canvas(main_frame)
canvas.pack(side=LEFT, fill=BOTH, expand=1) 

#Add A Scrollbar to the Canvas 
scrollbar = Scrollbar(main_frame, orient=VERTICAL, command=canvas.yview)
scrollbar.pack(side=RIGHT,fill=Y)

#Configure Canvas
canvas.configure(yscrollcommand=scrollbar.set)
canvas.bind('<Configure>',  event)

#Create another Frame inside the Canvas
imageframe = Frame(canvas)

#add that new frame to a window in the canvas 
canvas.create_window((0,0), window=imageframe, anchor="nw")



num_images = len(images)
num_images_per_col = 4
num_rows = ceil(num_images/num_images_per_col)


for i in range(num_images_per_col): 
    imageframe.columnconfigure(i, weight=1)


index=0
for i in range(num_rows): 
    for j in range(num_images_per_col): 
        if index > num_images-1: 
            break
        img = images[index].img
        button_img = Button(imageframe,image=img, command=command,borderwidth=2)
        button_img.grid(row=i,column=j, pady=5)
        index += 1



root.mainloop()
python tkinter python-imaging-library screen photo
© www.soinside.com 2019 - 2024. All rights reserved.