python - 如何使动态对象名称分配给一个类?/ 如何创建多个对象名称不同的窗口 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桌面上,每条尾巴都是一个窗口
解决方案
我以前在不同的上下文中看到过这个问题,但通常它要求动态命名的变量。答案并不特定于 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
推荐阅读
- javascript - 使用 axios 发出 xml 请求时浏览器中出现 415(不支持的媒体类型)
- php - 字符串php的深色十六进制颜色
- artificial-intelligence - 我在游戏机里造吃豆人,怎么造幽灵来追吃豆人像AI贪婪
- php - PHP 5.4 自动加载器无法按预期使用命名空间
- node.js - 在 nodejs 中进行验证的 Mongodb 查询
- python - Jupyter Lab 交互式绘图:*:“FloatSlider”和“float”不支持的操作数类型
- python - 使用 Python 库或正则表达式的数字分钟持续时间
- java - 使用 WebSocket vs XMPP vs MQ 实时数据显示的解决方案
- javascript - .highcharts-button-symbol 图像
- android - 深度链接共享不适用于 facebook