【问题标题】:Why my image buttons are not appearing?为什么我的图像按钮没有出现?
【发布时间】:2014-04-10 22:48:16
【问题描述】:

我试图在我的图像背景上的某个位置放置两个图像按钮,但我的按钮没有出现。我认为他们的图像在背景后面。

我尝试使用placepack,均无效。可能是什么问题?

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()

谢谢

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    您的图片很可能在显示之前就被垃圾回收了。这是一个常见的 Tkinter 陷阱。换行试试:

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

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

    并使用

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

    等等

    这应该保留对您的图像的引用,阻止它被垃圾收集。

    【讨论】:

      【解决方案2】:

      除了保留对图像的引用之外,您还有这行的问题:

      self.grid()
      

      Application__init__ 方法中。它将框架网格化到窗口中,但是由于没有任何东西被打包或网格化到框架中,所以它永远不会扩展超过一个很小的框架,所以你只是看不到它里面的按钮。一个简单的解决方法是 pack 方法,在需要时将参数传递给 fill 窗口和 expand

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

      【讨论】:

      • 好的。我把grid()改成了pad(),现在好像好多了。我可以看到我的背景图像和按钮,但看不到 BG 图像顶部的按钮。你知道我该如何解决这个问题吗?
      • 将带有背景图像的标签移动到框架中。打包框架后,放置背景图像,然后创建小部件。
      • 抱歉我还是没听懂。
      • 您没有将包含图像的标签分配给父级。如果在Application类的构造函数中创建Label,可以把它和按钮放在同一个Frame里,然后在按钮下面画出来。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 2022-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多