好的,所以我正在尝试找到Tkinter正在使用的框架,然后确定其宽度和高度,并调整窗口大小,使所有内容都很好地适应,而不会留下难看的空间。到目前为止,我得到了以下内容。。。
convert = {"tab1_name", "tab1"; "tab2_name", "tab2"; "tab3_name", "tab3") ##(it goes on)
a = mainframe.tab(mainframe.select(), "text")
b = convert[a]
w = b.winfo_reqwidth()
h = b.winfo_reqheight()
mainframe.configure(width=w, height=h)
笔记本中每个框架的名称是tab1、tab2、tab3等,但它们上的标签是唯一的,因为它们描述了选项卡中发生的事情。我希望能够将convert dictionary函数返回的字符串用作框架的名称。我不确定这个框架是一个类还是其他什么。有没有办法将字符串b转换为帧的名称,并以某种方式在.winfo_reqheight()中使用它?我不想做一件说。。。
if b=="tab1":
w = tab1.winfo_reqwidth()
h = tab1.winfo_reqheight()
mainframe.configure(width=w, height=h)
对于每一帧,因为我希望添加新帧变得容易,而不必添加太多代码。
感谢
选项1:
您可以将实际对象存储在字典中。所以试试:
convert = {"tab1_name": tab1, "tab2_name": tab2, "tab3_name": tab3}
a = mainframe.tab(mainframe.select(), "text")
b = convert[a]
w = b.winfo_reqwidth()
h = b.winfo_reqheight()
mainframe.configure(width=w, height=h)
选项2:使用"exec(字符串中的二进制代码)"函数可以执行字符串
请参阅如何在Python中执行包含Python代码的字符串?。
你可以这样做:(字典里只有文本或任何转换)
convert = {"tab1_name": "tab1", "tab2_name": "tab2", "tab3_name": "tab3"}
a = mainframe.tab(mainframe.select(), "text")
b = convert[a]
code1 = "w = %s.winfo_reqwidth()" % b
code2 = "h = %s.winfo_reqheight()" % b
exec(code1) # for python 2 it is: exec code1
exec(code2) # python 3 changed the exec statement to a function
mainframe.configure(width=w, height=h)
注意不要让恶意代码进入exec语句,因为python会运行它。通常只有当最终用户可以向函数中输入内容时,这才是问题(听起来你不必担心这一点)。
顺便说一句,我认为你的第一句话不正确。你用一个(但用)结束。正确的字典语法是:
convert = {"tab1_name": "tab1", "tab2_name": "tab2", "tab3_name": "tab3"}
请注意分隔键和值的冒号,以及条目之间的逗号。