Convert string into a Tkinter notebook frame

236 views Asked by At

Ok so I am trying to find the frame which Tkinter is using, then take its width and height and resize the window so that everything fits nicely without ugly spaces left. So far I have gotten the following...

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)

The names of each frame in the notebook are tab1, tab2, tab3, etc., but the labels on them are unique because they describe what happens in the tab. I want to be able to take the string returned from the convert dictionary function and use it as the frame's name. I am not sure if the frame is a class or what else. Is there a way to convert the string b into the frame's name and somehow use it in the .winfo_reqheight()? I do not want to have to make a thing which says...

if b=="tab1":
    w = tab1.winfo_reqwidth()
    h = tab1.winfo_reqheight()
    mainframe.configure(width=w, height=h)

for each frame because I want it to be easy to add new frames without having to add so much code.

Thank you

1

There are 1 answers

4
Kory On BEST ANSWER

Option 1:

You can store actual objects in dictionaries. So try:

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)

Option 2: Executing strings is possible with the 'exec('arbitrary code in a string')' function

See How do I execute a string containing Python code in Python?.

You could do this: (with just text in the dictionary or whatever convert is)

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)

Be careful that you don't let malicious code into the exec statement, because python will run it. This is usually only a problem if an end user can input things into the function(it sounds like you don't have to worry about this).


btw, I think your first line is incorrect. You open with a { but close with ). Proper dictionary syntax would be:

convert = {"tab1_name": "tab1", "tab2_name": "tab2", "tab3_name": "tab3"}

Notice the colons separating key and value, and commas in-between entries.