2

There are lot answer on stackoverflow
that say "to width of the widget one shoud use winfo_width()".

e.g. Get Tkinter Window Size

Could anybody point me to what I'm doing wrong?

My example code:

import Tkinter as tk


class App(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self._make_new_window()
        print 'self.winfo_width()', self.winfo_width()
        print 'self.text_window.winfo_width()', self.text_window.winfo_width()

    def _make_new_window(self):
        self.text_window = tk.Text(tk.Toplevel(self.master))
        self.text_window.pack()


root = tk.Tk()
app = App(master=root)
app.mainloop()

Actual result (printed on commandline):

self.winfo_width() 1
self.text_window.winfo_width() 1

This is strange because:

  • self.text_window is definitely not the same size as self
  • very strange measurement units

Expected result:

self.winfo_width() 30
self.text_window.winfo_width() 100

At least something allong these lines.




BTW.
This is on python 2.7.
Help info does not reveal anything usefull.

Help on method winfo_width in module Tkinter:

winfo_width(self) method of __main__.App instance
    Return the width of this widget.

EDIT - Solution:

  • Size can be retrieved only after window is drawn; It's possible to use self.update()) (Get Tkinter Window Size)
  • Need to use self.master.winfo_width() instead of self.winfo_width() for App (comment from fhdrsdg)

Fixed version looks like this:

import Tkinter as tk

help(tk.Frame)

class App(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self._make_new_window()
        self.update() # add update
        print 'self.master.winfo_width()', self.master.winfo_width() # use self.master
        print 'self.text_window.winfo_width()', self.text_window.winfo_width()

    def _make_new_window(self):
        self.text_window = tk.Text(tk.Toplevel(self.master))
        self.text_window.pack()


root = tk.Tk()
app = App(master=root)
app.mainloop()

Ouput is:

self.master.winfo_width() 108
self.text_window.winfo_width() 404
Community
  • 1
  • 1
industryworker3595112
  • 3,419
  • 2
  • 14
  • 18
  • 1
    Oh and you probably want `self.master.winfo_width()` instead of `self.winfo_width()` – fhdrsdg Sep 30 '14 at 07:11
  • I've updated my answer in the [Get Tkinter Window Size](http://stackoverflow.com/questions/4220295/get-tkinter-window-size/4221002#4221002) question to help solve your problem. – Bryan Oakley Sep 30 '14 at 11:00
  • @BryanOakley 1st of all I would like to thank you for the updated answer. 2nd, this question is definitely not a duplicate if you had to specifically amend your answer to address my question (thought this probably doesn't really matter I, my problem is solved) – industryworker3595112 Oct 01 '14 at 05:52

0 Answers0