Garry February 2016

tkinter window not wide enough to display window title

Is there a 'standard' way of ensuring that the displayed window is wide enough to display the window title?

import tkinter as tk
root = tk.Tk()
root_f = tk.Frame(root)
root.title('Long Window Title Containing Much Text')
text_f = tk.Frame(root_f)
text_l = tk.Label(text_f, text='Short text')

root_f.grid()
text_f.grid()
text_l.grid()

root.geometry('+{}+{}'.format(100, 100))
root.mainloop()
root.quit()

When I use the winfo method to get the width of the root (or text) frames they give the size of the text not the size of a window wide enough to display the whole window title.

I know it has to be something simple, but I can't see it.

Thanks

Answers


Bryan Oakley February 2016

No, there is no standard way. Tkinter has no way of knowing how long the title is on the titlebar. The OS / window manager has completely control of that portion of the window and doesn't expose any platform-independent way of getting at that information.

You would have to know not only the font used by the OS for window titles, but also whether there were any other decorations (eg: buttons, images, etc) that appear in the title area.

If you're fine with making assumptions that the font is the same as the default tkinter font, you can use tkinter's ability to measure the length of a string in a given font with the measure method of a font object.


odonckers February 2016

I found an answer which may work with some computers but not all. So this is just a concept.

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

titletext = "Long Long Long"
tk = Tk()
tk.title(titletext)
tk.resizable(0, 0)
canvas = Canvas(tk, width=100, height=100, bd=0, highlightthickness=0)
canvas.pack()
tk.update()

length = tk.winfo_width() / 4 - 23

if len(titletext) >= length:
        tk.title("Short")
        tk.update()

tk.mainloop()
tk.quit()

I had to change the code for my computer, but this should work. Please tell me if you find something wrong or if it works. And, at the top that 'try' and 'except ImportError' is to find which version of Python you have. If you want to change the original text of the navbar, change the variable 'titletext'. The only downside is that it is not a 'standard' way to do it.

Post Status

Asked in February 2016
Viewed 1,163 times
Voted 9
Answered 2 times

Search




Leave an answer