将图像添加到 Tkinter [英] Adding image to Tkinter
问题描述
我在 tkinter 的代码中添加了一个图像文件,但它基本上填满了我的整个框架,所以如果可能的话,你能推荐一个教程来展示或解释如何做到这一点......除非你可以在这里展示.
I have added a image file to my code in tkinter but it basically fills my the whole frame so if its possible can you recommend a tutorial that shows or explains how to do this.... unless you can show me on here.
我还没有添加我的完整代码,但是一旦你将它保存在 python 目录中,下面的代码应该会显示一个测试图像.
I havent added my full code but the code below should display a test image once you have it saved in the python directory.
我想创建下一步"按钮,它会打开一个带有另一张图像的新框架.
I would like to create 'next' button which would open up a new frame with another image on it.
from Tkinter import *
root = Tk()
ButtonImage = PhotoImage(file='test.gif')
testButton = Button(root, image=ButtonImage)
testButton.pack()
root.mainloop()
推荐答案
你可以试试这样的:
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
方法循环浏览图像并使用configure
<将新图像绑定到PhotoImage
/li>
glob
is used to get a list of all files matching some pattern in the current directorygrid
is a simple but quite flexible layout manager for Tkinter (see Tkinter reference)- the
show_next
method, which is bound to the button, cycles through the images and binds a new image to thePhotoImage
usingconfigure
结果是一个简单的框架,显示一个大图像和一个按钮,循环浏览当前目录中的 gif
图像.
The result is a simple frame showing a large image and a button, cycling though the gif
images in the current directory.
这篇关于将图像添加到 Tkinter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!