首页 > 解决方案 > 如何使动态对象名称分配给一个类?/ 如何创建多个对象名称不同的窗口 Tkinter

问题描述

我正在使用 Tkinter,我想创建很多窗口,但是每个窗口都有不同的对象名称,所以我可以单独移动它们。

例子:

def window(self):
        
        self.window1 = Tk()

        sizexcenter = str(int(self.root.winfo_screenwidth() / 2 - 20))
        sizeycenter = str(int(self.root.winfo_screenheight() / 2 - 20))


        self.window1.geometry('40x40' + '+' + sizexcenter + '+' + sizeycenter)
        self.window1.overrideredirect(1)
        self.window1.mainloop()

并且下次调用这个函数的时候

def window(self):
        
        self.window2 = Tk()

        sizexcenter = str(int(self.root.winfo_screenwidth() / 2 - 20))
        sizeycenter = str(int(self.root.winfo_screenheight() / 2 - 20))


        self.window2.geometry('40x40' + '+' + sizexcenter + '+' + sizeycenter)
        self.window2.overrideredirect(1)
        self.window2.mainloop()

以此类推,适用于贪吃蛇游戏,但在windows桌面上,每条尾巴都是一个窗口

标签: pythontkinter

解决方案


我以前在不同的上下文中看到过这个问题,但通常它要求动态命名的变量。答案并不特定于 Tkinter。您通常想要找到的是字典。

    self.windows = {}
    self.windows['window1'] = Tk()
    self.windows['window2'] = Tk()

是的,有一些方法可以用getattr/动态创建变量,setattr但它们确实是对于 adict非常有意义的事情的较低级别的解决方案。

更新:

如果您并不真正关心按名称随机访问这些对象并且只想继续创建新窗口,那么附加到列表可能更合适,因为这会增加您的蛇并维持秩序。

    self.windows = []
    self.windows.append(Tk())
    self.windows.append(Tk())

    self.windows[0].foo
    self.windows[1].bar

推荐阅读