python - 更改背景使其标签消失
问题描述
我想构建一个应用程序,您可以通过单击按钮来更改背景图像。首先,为了给我的框架添加背景,我将图像创建为标签,然后将所有其他标签子分类为背景标签。现在,当您单击“更改背景”按钮时,它会更改背景。但是,所有标签都消失了。仅当您将光标悬停在按钮上时才会出现按钮。标签永远不会出现!我的问题是:
- 为什么会这样?
- 如何解决?
这是重现该问题的简单代码:
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()
解决方案
推荐阅读
- google-chrome-extension - 拒绝执行内联脚本
- docker-compose - 基于当前操作系统的条件图像使用
- amazon-web-services - 如何在 Codebuild 中将 AWS 凭证传递给 docker compose 网络
- c - 在getchar()循环中如何检测C字符串中的最后一个字符
- java - 如何在程序运行后将原始用户输入显示到最终输出中?
- azure-pipelines-release-pipeline - 如何在 Azure-DevOPS 发布管道中使用 XML 转换进行 IIS 部署?
- java - findall() 并不总是从数据库中提取值吗?
- r - Filter() 使用来自变量的值作为参数
- java - 内部bean创建的spring顺序
- three.js - 使用 OrbitControls 自动旋转在three.js 中居中枢轴点