Tkinter背景与重叠的按钮?

时间:2018-12-19 20:58:35

标签: python tkinter

我已经创建了一个记分牌,我想为其添加背景。如果我不使用背景图像,则会显示我的按钮,但是当我使用背景图像时,我的按钮会“消失”。这是我的代码的一小部分,如何将按钮放在背景的前面?感谢您的帮助。

from tkinter import *


player1health = 100
player2health = 100
player3health = 100
player4health = 100


class Window(Frame):

    def __init__(self, master = None):
        Frame.__init__(self, master)
        self.master = master
        self.init_window()

    def init_window(self):
        self.master.title("Scoreboard")
        self.pack(fill=BOTH, expand = 1)

        # Background
        image1 = PhotoImage(file="C:/Users/Ahmet/OneDrive/Desktop/SC/achtergrond1.png")
        w = image1.width()
        h = image1.height()
        root.geometry("600x500")
        panel1 = Label(root, image=image1)
        panel1.pack(side='top', fill='both', expand='yes')
        panel1.image = image1

        #Player1
        self.Name1 = Label(root, text = input("Name player 1: "), font=("Helvetica", 16))
        self.Name1.place(x=80,y=50)

        #scoretracker
        self.Score1 = Label(root,text= 'Score:' )
        self.Score1.place(x=55, y=80)

        self.L1 = Label(root,text= player1health )
        self.L1.place(x=100, y=80)

        self.HP1 = Label(root,text= 'HP' )
        self.HP1.place(x=125, y=80)

        self.add = Label(root, text = "Add",font=("Helvetica", 13))
        self.add.place(x = 30,y=120)
        #button
        player_1_add_10_Button = Button(self, text = "10 HP",)
        player_1_add_10_Button.place(x=30,y=140)

        player_1_add_20_Button = Button(self, text = "20 HP",)
        player_1_add_20_Button.place(x=30,y=170)

        player_1_add_30_Button = Button(self, text = "30 HP",)
        player_1_add_30_Button.place(x=30,y=200)


root = Tk()
root.geometry("600x500")
root.configure(background="light blue")
Label(root, text='Scoreboard:', bg= 'light blue').pack()

app = Window(root)
root.mainloop()

1 个答案:

答案 0 :(得分:1)

包含背景图像的标签是root的从属。您在init_window()函数中创建的标签也是如此,但是按钮是self的从属。

所以,而不是:

panel1 = Label(root, image=image1)

尝试

panel1 = Label(self, image=image1)

并对所有按钮也进行相同的更改。那应该更好。