【问题标题】:How do I make my Label Tkinter element display?如何使我的 Label Tkinter 元素显示?
【发布时间】:2020-04-14 22:53:48
【问题描述】:

目前,我正在创建一个文字冒险游戏。现在,为了让它比许多使用 python 控制台的软件好一点,我正在使用 Tkinter 来制作 GUI。只有它显示我的开始屏幕的背景图像,而不是我放在那里的文本!请帮忙!

# writes the title as text in the window
titleFont = tkFont.Font(family = "Comic Sans MS", size = 20)
titleText = tkinter.Label(app, text="Gods of This World", font=titleFont)
titleText.pack()

# sets the background image to the games 3 colors (Red, Green, Grey)
C = tkinter.Canvas(app, height=300, width=250)
filename = tkinter.PhotoImage(file = "C:/Users/" + getpass.getuser() + "/Desktop/Gods of This World/net/godsofthisworld/ui/images/backgroundimage.png")
background_label = tkinter.Label(app, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()

【问题讨论】:

  • 首先运行titleText.pack(),然后运行background_label.place(),这样它就可以将image 放在text 之上——你的text 可以隐藏在image 后面。把它放在不同的顺序。 BTW:如果你不使用canvas.create_image()canvas_create_text(),我不知道你为什么要创建Canvas
  • 好的等等,别介意我用画布添加文本,这样它就不会用灰色背景覆盖我的图像。

标签: python tkinter


【解决方案1】:

你把图片放在文本之后——你使用.place(x=0, y=0, relwidth=1, relheight=1)——所以文本隐藏在图片后面。

按不同的顺序排列 - 第一张图片,下一个文字。

import tkinter as tk

app = tk.Tk()

# first image   
photo = tk.PhotoImage(file="image.png")
background_label = tk.Label(app, image=photo)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

# next text   
titleText = tk.Label(app, text="Gods of This World")
titleText.pack()

app.mainloop()

顺便说一句: label 带有文本将有灰色背景 - 您无法将其删除。如果您想要没有背景的文本,请使用Canvascanvas.create_image()canvas.create_text() - 没有pack()place()

import tkinter as tk

WIDTH = 800
HEIGHT = 600

app = tk.Tk()

canvas = tk.Canvas(width=WIDTH, height=HEIGHT)
canvas.pack()

photo = tk.PhotoImage(file="image.png")
canvas.create_image((WIDTH/2, HEIGHT/2), image=photo) #, anchor='center')
canvas.create_text((WIDTH/2, HEIGHT/2), text="Gods of This World") #, anchor='center')

app.mainloop()

【讨论】:

  • 非常感谢!它成功了,现在我可以添加开始游戏按钮了!
  • 顺便说一句:您可以使用canvas.create_window((x, y), window=tk.Button(...), ...)Button(或任何其他小部件)放在Canvas 上。 effbot.org 文档:Canvas
猜你喜欢
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
相关资源
最近更新 更多