【问题标题】:I can't figure out how to put buttons on top off my background picture, I've tried many forums, but none off the answers worked我不知道如何将按钮放在背景图片的顶部,我尝试了很多论坛,但答案都没有
【发布时间】:2019-02-24 11:11:48
【问题描述】:

所以我正在为我的游戏制作一个“HUB”,并在那里获得了我的背景,但我无法在背景上显示按钮。我在许多论坛上进行了搜索,但没有一个答案适用于我的脚本。不知道我需要做什么。该脚本非常简单,因为它只是一个 HUB。

编辑:所以我做了一些更改,现在我有按钮和图片,但我不能将两个按钮都放在图片上。就像图片本身就是一排一样。

这是脚本:

from tkinter import *

root = Tk()
root.geometry("1280x640")
root.title("Choose level")
topFrame = Frame(root, width=1280, height=640)
topFrame.grid(row=0)

background = PhotoImage(file="HUB_BG.png")
background1 = Label(root, image=background)
background1.grid(row=0)

level1 = Button(topFrame, text="Level 1")
level1.grid(row=0)
level2 = Button(topFrame, text="Work in progress")
level2.grid(row=1)
#level3
#level4
#level5
#level6
#level7
#level8
#level9
#level10

root.mainloop()

【问题讨论】:

  • 您的顶框没有网格化或打包,所以里面的任何东西都不会显示。
  • 是的,我意识到了。等一下
  • 仍然没有做任何事情,除了把事情搞砸了一点。现在我真的不能把两个按钮都放在图片中
  • 如果只是按钮需要在图片中,将它们与您的背景一起加载为它们的父项?

标签: python-3.x tkinter


【解决方案1】:

我已经调整了您的代码以在我这边工作.. 只需进行一些调整即可实现我认为您想要的结果:-)

你可能想记录一下columnconfigure和rowconfigure,以及grid方法的sticky参数。

from tkinter import *    
root = Tk()
root.geometry("1280x640")
root.title("Choose level")

# Let's assume we are not using your frame.
#topFrame = Frame(root, width=1280, height=640)
#topFrame.grid(row=0)

background = PhotoImage(file="HUB_BG.png")
background1 = Label(root, image=background)

# adding a column to use columnconfigure and rowconfigure...
# using sticky so the image stays expanded in your widget
background1.grid(column=0, row=0, sticky='nsew')
# Below will stick your background label so it doesn't resize with your widgets
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

# replaced topframe with background1.
level1 = Button(background1, text="Level 1")
level1.grid(row=0)
level2 = Button(background1, text="Work in progress")
level2.grid(row=1)

【讨论】:

    【解决方案2】:

    使用背景图片最简单的解决方案是使用place 将图片添加为背景。 place 不会改变父级的大小或父级中任何其他小部件的布局,并且可以像往常一样使用gridpack 在顶部添加其他小部件。

    请注意,在创建其他小部件之前创建图像小部件非常重要,以便它在堆叠顺序中较低。或者,您可以在小部件上调用lower() 方法将其移动到堆叠顺序的底部。

    例子:

    background1.place(relx=.5, rely=.5, anchor="c")
    

    【讨论】:

    • 谢谢,我以后一定会用这个!
    猜你喜欢
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    相关资源
    最近更新 更多