动态创建的按钮出现在另一个Python Tkin上

2024-04-26 03:47:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题。我使用类动态创建按钮。每个按钮都存储在一个列表中,因此我可以稍后通过索引来使用它们。不过,我在放置/显示按钮时遇到了问题。当我创建一个按钮时,它会完美地显示出来。当我创建另一个时,由于某种原因它会出现在第一个上面。如能帮助解决此问题,我们将不胜感激。谢谢!你知道吗

代码如下:

import tkinter as tk

window = tk.Tk()
window.geometry('800x600')
placeX = 20
placeY = 20
bl = []

def direction(type_):
    pass

class SideBar():
    def __init__(self, name):
        global window
        global placeX
        global placeY
        global bl
        self.name = name
        self.placeX = placeX
        self.placeY = placeY
        self.bl = bl
        self.bl.append(self.name)
        print(self.bl)

    def create_folder(self, index):
        self.bl[index] = tk.Button(window, text = self.name, command = lambda: direction(self.name))
        self.bl[index].config(height = 3, width = 6)
        self.bl[index].place(x = self.placeX, y = self.placeY)
        self.placeY += 100


Computer = SideBar('Computer')
Documents = SideBar('Documents')

Computer.create_folder(0)
Documents.create_folder(1)

window.mainloop()

我认为问题出在create\u folder函数的某个地方。你知道吗


Tags: nameselfindexdefcreatefolderwindow按钮
2条回答

您正在创建一个类的两个不同实例。两者都有各自的局部变量。创建一个实例并使用以下内容:

import tkinter as tk

window = tk.Tk()
window.geometry('800x600')
placeX = 20
placeY = 20
bl = []

def direction(type_):
    pass

class SideBar():
    def __init__(self):
        global window
        global placeX
        global placeY
        global bl
        self.name = []
        self.placeX = placeX
        self.placeY = placeY
        self.bl = []
        self.bl.append(self.name)

    def create_folder(self, index, name):
        self.name.append(name)
        self.bl.append(tk.Button(window, text = self.name[-1], command = lambda: direction(self.name)))
        self.bl[-1].config(height = 3, width = 6)
        self.bl[-1].place(x = self.placeX, y = self.placeY)
        self.placeY += 100


side_bar = SideBar()
#Documents = SideBar('Documents')

side_bar.create_folder(0, 'Computer')
side_bar.create_folder(1, 'Documents')

window.mainloop()

您可能打算使用类变量而不是实例属性。class变量保存类的所有实例之间共享的数据,事实上,只要有类定义,它就可以有一个值。而实例属性可以具有特定于类的单个实例的值,通常采用self.attribute格式。你知道吗

您尝试使用self.placeY的方式符合类变量的典型用法。删除:

self.placeY = placeY

添加:

class SideBar():
    ...
    placeY = placeY #assign global placeY's value to Sidebar.placeY
    ...

最后,替换:

self.placeY += 100

使用:

SideBar.placeY += 100

相关问题 更多 >