Tkinter - 尽管保留了全局参考,但图像不会显示在按钮上 [英] Tkinter - Image won't show up on button despite keeping global reference

查看:38
本文介绍了Tkinter - 尽管保留了全局参考,但图像不会显示在按钮上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在右上角放置一个按钮并使该按钮成为图像.我了解范围界定/垃圾收集等,并且已经看到这里提出的所有其他问题都忽略了这一事实.

I want to place a button in the upper right corner and have the button be an image. I understand about scoping/garbage-collection etc. and have seen all the other questions asked here that overlook this fact.

然而,我尝试了很多方法,包括创建一个 self.photo 和将 photo 声明为一个全局变量.实际上,我什至不相信这是问题所在,因为我将照片声明在与调用 mainloop() 相同的范围内.

However, I have tried numerous methods including creating a self.photo and declaring photo as a global variable. I'm actually not even convinced that that's the issue, because I declare the photo in the same scope as I call the mainloop().

我现在的代码(主要从使用overrideredirect时拖动窗口因为我对 tkinter 不是很熟悉):

My code right now (which is mostly borrowed from Drag window when using overrideredirect since I'm not really familiar with tkinter):

import tkinter

pink="#DA02A7"
cyan="#02DAD8"
blue="#028BDA"

class Win(tkinter.Tk):

    def __init__(self,master=None):
        tkinter.Tk.__init__(self,master)
        self.overrideredirect(True)
        self._offsetx = 0
        self._offsety = 0
        self.bind('<Button-1>',self.clickwin)
        self.bind('<B1-Motion>',self.dragwin)
        self.geometry("500x500")

    def dragwin(self,event):
        x = self.winfo_pointerx() - self._offsetx
        y = self.winfo_pointery() - self._offsety
        self.geometry('+{x}+{y}'.format(x=x,y=y))

    def clickwin(self,event):
        self._offsetx = event.x
        self._offsety = event.y

win = Win()

# put a close button
close_button = tkinter.Button(win, bd=0, command=win.destroy)
global photo
photo=tkinter.PhotoImage("close.gif")
close_button.config(image=photo, height="10", width="10")

# pack the widgets
close_button.pack(anchor=tkinter.NE)

win.configure(bg=pink)

win.mainloop()

推荐答案

我通常给 PhotoImage 一个名称并在 image 参数中使用该名称:

I typically give PhotoImages a name and use the name in image parameters:

photo=tkinter.PhotoImage(name='close', file="close.gif")
close_button.config(image='close')

我不确定这是否是唯一的方法,但这在这里有效.

I'm not sure if this is the only way, but this works here.

这篇关于Tkinter - 尽管保留了全局参考,但图像不会显示在按钮上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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