【问题标题】:Background image using Tkinter - Python 2.7使用 Tkinter 的背景图像 - Python 2.7
【发布时间】:2015-08-30 13:42:07
【问题描述】:

我正在尝试在图像上显示一个按钮。该按钮似乎位于图像的前面。 如何将图像设置为应用程序的背景? 按钮也需要改变他的位置,所以图像应该是永久的。

我的代码:

from Tkinter import *

class App:
def __init__(self,master):
    frame = Frame(master)
    master.geometry("400x200")
    frame.pack()

    self.hello_b = Button(master,text="ME",command=sys.exit, height=1, width=3,fg= "blue",bg = "green")
    self.hello_b.pack()


    photo = PhotoImage(file="unnamed.gif")
    w = Label (master, image=photo)
    w.place(x=0, y=0, relwidth=1, relheight=1)
    w.photo = photo
    w.pack()


root = Tk()
app = App(root)
root.mainloop()

【问题讨论】:

  • 有几处错误。有很多代码与您的问题无关,这意味着您在测试之前编写了太多代码。写并发布一个 mcve stackoverflow.com/help/mcve。您创建并打包了一个未使用的框架。您在打包的 Button 顶部放置了一个带有照片的标签。然后您再次打包照片。
  • 我编辑并清理了一些东西。我希望现在它更清楚了。
  • 我在 3.5 中对 .png 的实验表明需要设置 w.photo 属性,但这非常不寻常,并且不在我拥有的 tkinter 文档中。你怎么知道这样做的?
  • 通过互联网.. 我对 python 很陌生,并试图从我能阅读的内容中收集知识。我有想要展示的 .gif 文件并使用了它。您能否建议一种在背景中显示 .gif 的方法,而按钮位于其上方?

标签: python image python-2.7 button tkinter


【解决方案1】:

我怀疑的答案是here:“[代码]将一个Label小部件打包在一个框架小部件中,然后在框架的右上角放置一个Button。按钮将与标签重叠。 "我是这样测试的

from tkinter import *

class App:
    def __init__(self,master):
        master.geometry("400x200")

        photo = PhotoImage(file="C:/programs/Python34/temimage.png")
        self.w = w = Label (master, image=photo)
        w.photo = photo
        w.pack()

        self.hello_b = Button(master,text="ME",command=sys.exit, height=1,
                              width=3,fg= "white",bg = "green")
        self.hello_b.place(x=200, y=5)

root = Tk()
app = App(root)
root.mainloop()

按钮确实在图像的顶部。 x,y 位置似乎是按钮的左上角。添加

def move():
    app.hello_b.place(x=100, y=100)
root.after(1000, move)

导致按钮在一秒钟后跳转,正如预期的那样。

【讨论】:

  • 非常感谢。我怀疑这是问题所在,但早些时候取消了该选项。如果可以的话,还有一件事:按钮应该在点击时关闭程序,但它只会使程序崩溃。如何使 sys.exit 正常工作(或任何其他方法)?
  • root.destroy -- 请参阅 Python 参考章节中关于 tkinter 的示例。 SO上可能还有其他答案。 root.destroy 停止 root.mainloop。 Python 执行文件中的任何代码,如果没有,则正常退出。直接使用 sys.exit 是不常见的。
猜你喜欢
  • 2014-05-08
  • 1970-01-01
  • 2017-10-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多