微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

调用 canvas.create_window() 时按钮不显示

如何解决调用 canvas.create_window() 时按钮不显示

我在 python 中使用了 tkinter,我想在画布屏幕上添加一些按钮。但是当我运行脚本时,按钮没有显示在屏幕上。这有点复杂,但我从 for 循环创建按钮,然后将它们附加到列表中。

这是我的代码

from tkinter import * 

class Application:
    def __init__(self): 
        self.window = Tk()
        self.window.geometry("1280x720")
        self.window.resizable(False,False)        

        self.initHomeWindow()

        self.window.mainloop()

    def initHomeWindow(self):
        def initButtons():
            self.buttonList = []
            self.button_load = {}
            self.button = {}

            imgInfo = [
                    ['Abs','105','425.97','310'],#1st one is button itself,2nd one is width of the button,3rd one is the x-position of the button,4th one is y-position of the button. 
                    ['Arms','123','370'],['Back','117','430'],['Calves','128','848','314.5'],['Delts','121','490'],['glutes','364.5'],['Hams','127','414.5'],['pecs','112','550'],['Quads','464.5'],['Traps','126','610']
            ]

            for x in range(len(imgInfo)):
                self.button[str(imgInfo[x][0])] = Button(self.window,width=int(imgInfo[x][1]),height=49)

                self.buttonList.append([self.button[str(imgInfo[x][0])],imgInfo[x][2],imgInfo[x][3]])

        initButtons()

        self.window.overrideredirect(False)
        self.window.geometry("1280x720")

        self.canvas2 = Canvas(self.window,highlightthickness=0,bg="#1b1b1b")
        self.canvas2.pack(fill=BOTH,expand=TRUE)

        for x in range(len(self.buttonList)):
            self.canvas2.create_window(float(self.buttonList[x][1]),float(self.buttonList[x][2]),window=self.buttonList[x][0])

Application()

enter image description here

当我运行脚本时,按钮没有显示在屏幕上(见图)

希望有人能帮我解决这个问题,提前致谢!

解决方法

由于您创建按钮和画布的顺序以及按钮是根窗口的子窗口而不是画布的事实,您的按钮位于 z 轴上的画布下方。

最好将按钮设为画布的子级,但您也可以使用 lift 方法将按钮按堆叠顺序升高:

for x in range(len(self.buttonList)):
    self.buttonList[x][0].lift()
    ...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。