简体   繁体   中英

How do I get the size of a pygtk window?

I'm trying to use gtk.window.get_size(), but it always just returns the default width and height. The documentation says

The get_size() method returns a tuple containing the current width and height of the window. If the window is not on-screen, it returns the size PyGTK will suggest to the window manager for the initial window size. The size obtained by the get_size() method is the last size received in a configure event, that is, PyGTK uses its locally-stored size, rather than querying the X server for the size. As a result, if you call the resize() method then immediately call the get_size() method, the size won't have taken effect yet. After the window manager processes the resize request, PyGTK receives notification that the size has changed via a configure event, and the size of the window gets updated.

I've tried resizing the window manually and waiting a minute or so, but I still get the default width and height.

I'm trying to use this to save the window size on quit so that I can restore it on start. Is there a better way to do this?

Here's the code snipit I have for my main quit.

def on_main_window_destroy(self, widget, data=None):
    if self.view.current_view.layout == 'list':
        self.view.current_view.set_column_order()

    width = self.main_window.get_size()[0]
    height = self.main_window.get_size()[1]
    #test statement
    print (width, height)

    self.prefs.set_size_prefs(width, height)
    self.prefs.set_view_prefs(self.view.current_view.media, self.view.current_view.layout)
    gtk.main_quit()

I think I understand what's happening now. This is inside the destroy signal, so by the time the code gets called, the window is already gone. Is there a more canonical way of handling window resizing? I was hoping to avoid handling resize events everytime the user resized the window.

This seems to fix your problem:

import gtk

def print_size(widget, data=None):
    print window.get_size()

def delete_event(widget, data=None):
    print window.get_size()
    return False

def destroy(widget, data=None):
    gtk.main_quit()

window = gtk.Window()
window.connect('delete_event', delete_event)
window.connect('destroy', destroy)

button = gtk.Button(label='Print size')
button.connect('clicked', print_size)
window.add(button)

window.show_all()

gtk.main()

I think the key is calling get_size on the delete_event signal rather than the destroy signal. If you do it on the destroy signal, it's like you describe, it just returns the default size.

Try running:

while gtk.events_pending():
    gtk.main_iteration_do(False)

right before calling window.get_size()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM