将图像添加到 tkinter gui [英] adding image to tkinter gui

查看:37
本文介绍了将图像添加到 tkinter gui的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Tkinter 的新手.我想创建一个可以支持嵌入音频文件并且还具有背景图像的 GUI.我无休止地尝试安装 pygame 无济于事.我似乎无法弄清楚为什么它没有正确安装,所以此时我只是想找到最简单的方法来拥有这两个选项.下面是我尝试使用画布小部件显示背景图像.但是,我总是收到一个错误,我的变量没有定义.我真的很感激一些关于我做错了什么的反馈,以及任何不仅仅涉及基础知识的有用的 tkinter 教程.提前致谢

I am new to Tkinter. I want to create a GUI that can support embedding audio files and that also has a background image. I have tried endlessly to install pygame to no avail. I cannot seem to figure out why it is not installing correctly so at this point I am just trying to find the easiest way possible to have these two options. Below is my attempt at displaying a background image using a canvas widget. However, I always get an error that my variables are not defined. I would really appreciate some feedback on what I am doing wrong, as well as any helpful tkinter tutorials that involve more than just the basics. Thanks in advance

from Tkinter import *   

root = Tk()
root.geometry("500x500")

class Application(Frame):

    def __init__(self, master):
        #initialize the frame
        Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.can = Canvas(root, width=160, height=160, bg='white')
        self.pic = PhotoImage(file='speaker.gif')
        self.item = can.create_image(80, 80, image=pic)

app = Application(root)

#kick off event loop
root.mainloop()

推荐答案

每次你想在一个类的方法中使用它的属性时,你需要在它的前面加上 self. 前缀:

Every time you want to use an attribute of a class inside one of its methods, you need to prefix it with self.:

self.item = self.can.create_image(80, 80, image=self.pic)
#           ^^^^^                               ^^^^^

否则,Python 会将名称视为函数的本地名称,并在找不到它们时引发异常.

Otherwise, Python will treat the names as being local to the function and will raise an exception when it fails to find them.

此外,您忘记在画布小部件上调用 grid:

Also, you forgot to call grid on your canvas widget:

self.can = Canvas(root, width=160, height=160, bg='white')
self.can.grid(...)

<小时>

关于 Tkinter 的资源,您可以查看这些:


As for resources on Tkinter, you can check out these:

这篇关于将图像添加到 tkinter gui的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆