3

我已经在 tkinter 中的代码中添加了一个图像文件,但它基本上填满了我的整个框架,所以如果可能的话,你能推荐一个教程来展示或解释如何做到这一点......除非你可以在这里给我看。

我还没有添加我的完整代码,但是一旦你将它保存在 python 目录中,下面的代码应该会显示一个测试图像。

我想创建一个“下一步”按钮,它会打开一个带有另一个图像的新框架。

from Tkinter import *

root = Tk()
ButtonImage = PhotoImage(file='test.gif')
testButton = Button(root, image=ButtonImage)
testButton.pack()
root.mainloop()
4

2 回答 2

0

你可以尝试这样的事情:

from Tkinter import *
from glob import glob

class ImageFrame(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.images = glob("*.gif")
        self.cur = 0
        # label showing the image
        self.image = PhotoImage()
        imagelabel = Label(self, image=self.image)
        imagelabel.grid(row=1, column=1)
        # button cycling through the images
        button = Button(self, text="NEXT", command=self.show_next)
        button.grid(row=2, column=1)
        # layout and show first image
        self.grid()
        self.show_next()

    def show_next(self):
        self.cur = (self.cur + 1) % len(self.images)
        self.image.configure(file=self.images[self.cur])

ImageFrame().mainloop()

一些解释:

  • glob用于获取当前目录中匹配某个模式的所有文件的列表
  • grid是一个简单但非常灵活的 Tkinter 布局管理器(参见Tkinter 参考
  • 绑定到按钮的show_next方法循环浏览图像并将新图像绑定到PhotoImage使用configure

结果是一个简单的框架,显示一个大图像和一个按钮,循环浏览gif当前目录中的图像。

于 2013-03-13T10:20:46.260 回答
0

有许多模块可以帮助您解决这个问题。您可以使用 PIL 模块。通常,在像您这样的情况下,我会使用 PIL 模块将图像加载并粘贴到框架上。这就是你这样做的方式。

from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
Image       = Image.open(path).resize((300, 300)), Image.ANTIALIAS
ButtonImage = ImageTk.PhotoImage(Image)
# If you are using image by itself. Without it being a button. 
#Image_Label = Label(image = self.HomeImage, borderwidth=0, highlightthickness=0)
# Otherwise 
testButton = Button(root, image=ButtonImage)
testButton.pack()
root.mainloop()

我相信这肯定会帮助您调整图像大小并将图像作为按钮加载到屏幕上。我们使用 PIL 将图像加载到框架上并调整图像大小。这也是您之前要求的。我在 Image.open() 函数上使用了 resize 方法。这会将图像调整为您想要的大小。标准是该图像的实际尺寸。

于 2019-04-30T02:22:46.757 回答