首页 > 解决方案 > 更改背景使其标签消失

问题描述

我想构建一个应用程序,您可以通过单击按钮来更改背景图像。首先,为了给我的框架添加背景,我将图像创建为标签,然后将所有其他标签子分类为背景标签。现在,当您单击“更改背景”按钮时,它会更改背景。但是,所有标签都消失了。仅当您将光标悬停在按钮上时才会出现按钮。标签永远不会出现!我的问题是:

  1. 为什么会这样?
  2. 如何解决?

这是重现该问题的简单代码:

import tkinter as tk
from PIL import ImageTk, Image

class App():
    def __init__(self, root):
        self.root = root
        
        self.controlFrame = tk.Frame(root, width=900, height=600)
        self.controlFrame.pack_propagate(0)   # Prevents resizing
        self.controlFrame.pack()
        
        
        
        img = Image.open('images/outside.jpg').resize((900, 600))
        self.background_image = ImageTk.PhotoImage(img)        
        self.background_label = tk.Label(self.controlFrame, image=self.background_image)
        self.background_label.configure(image = self.background_image)
        self.background_label.pack(fill="both", expand="yes")
        
        
        
        self.changeButton = tk.Button(self.background_label, text="Change Background", 
                                    command = self.changeBK)
        self.changeButton.place(x=400, y=300)
        
        self.someButton = tk.Button(self.background_label, text="Some Button")                                    
        self.someButton.place(x=400, y=100)
        
        self.someOtherButton = tk.Button(self.background_label, text="Some Other Button")
        self.someOtherButton.place(x=400, y=450)
        
        self.userMessage = tk.Label(self.background_label, text="Label", height = 3 , width= 14, bg="white")
        self.userMessage.place(x=400, y= 200)
        
    def changeBK(self):
        img = Image.open('images/muddyPath.jpg').resize((900, 600))
        self.background_image = ImageTk.PhotoImage(img)
        self.background_label.configure(image = self.background_image)

def main():
    win = tk.Tk()                           # Create a window
    win.title("Using Multiple Layouts")     # Set window title
    win.geometry("900x600")                 # Set window size
    win.resizable(False, False)             # Both x and y dimensions ...

    # Create the GUI as a Frame
    # and attach it to the window ...
    myApp = App(win)

    # Call the GUI mainloop ...
    win.mainloop()

if __name__ == "__main__":
    main()

标签: pythontkinterspyder

解决方案


推荐阅读