简体   繁体   English

为什么我的图像按钮没有出现?

[英]Why my image buttons are not appearing?

I am trying to place two image buttons on my image background in a certain position, but my buttons are not appearing. 我试图将两个图像按钮放置在图像背景上的某个位置,但是我的按钮没有出现。 I think their images are behind the background. 我认为他们的图片背后有背景。

I tried to use place and pack , both did not work. 我尝试使用placepack ,但都没有用。 What could be the problem? 可能是什么问题呢?

from tkinter import*
import tkinter as tk
import settings

class Application(Frame):
    def __init__ (self, master):
        Frame.__init__(self,master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        button1 = PhotoImage(file ="button1.gif")
        button2 = PhotoImage(file ="button2.gif")
        settings_button = Button(self, image = button1, 
                                 command = self.mult_command, width = 15)
        settings_button.place(x=1, y=1)
        rules_button = Button(self, image = button2, 
                              command = self.the_rules, width = 15)
        rules_button.place(x=50, y=50)

def main_code():
    window = Tk()
    window.title("The Bouncer")
    bg_image = PhotoImage(file ="pic.gif")
    x = Label (image = bg_image)
    x.image = bg_image
    x.place(x = 0, y = 0, relwidth=1, relheight=1)
    window.geometry("600x300")
    app = Application(window)
    window.mainloop()

main_code()

thanks 谢谢

It is likely that your image is being garbage collected before it is displayed. 在显示图像之前,很可能已对其进行了垃圾收集。 This is a common Tkinter gotcha. 这是常见的Tkinter陷阱。 Try changing the lines: 尝试更改行:

button1 = PhotoImage(file ="button1.gif")
button2 = PhotoImage(file ="button2.gif")

to

self.button1 = PhotoImage(file ="button1.gif")
self.button2 = PhotoImage(file ="button2.gif")

and use 和使用

settings_button = Button(self, image = self.button1, command = self.mult_command, width = 15)

etc. 等等

This should keep a reference to your image, stopping it from getting garbage collected. 这应该保留对您的图像的引用,阻止其收集垃圾。

In addition to keeping a reference to the image, you have a problem with this line: 除了保留对图像的引用之外,此行还存在问题:

self.grid()

in the __init__ method of Application . Application__init__方法中。 It's gridding the Frame into the window, but since nothing is ever packed or gridded into the frame, it doesn't ever expand past a little, tiny frame, so you just don't see the Buttons inside it. 它正在将框架网格化到窗口中,但是由于没有任何东西被打包或网格化到框架中,所以它永远不会扩展到一个很小的框架上,因此您只是看不到其中的按钮。 A simple fix here would be the pack method, with arguments to fill the window and expand when needed: 一个简单的解决方法是pack方法,它具有fill窗口并在需要时expand参数:

self.pack(fill=BOTH, expand=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM