Skip to content

Using the tk.Toplevel Widget

Alejandro Autalán edited this page Jun 19, 2017 · 6 revisions

The tk.Toplevel widget was added to pygubu to replace the functionality of the TkApplication helper class. It allows to configure a Toplevel widget using the pygubu-designer.

Usage recomendations

  • Is better to use a Frame as the first and only child of the toplevel. This helps when you want to set the main window resizable. Then put all other widgets inside the frame.

Minimal example

Hello world program using the tk.Toplevel widget.

<?xml version='1.0' encoding='utf-8'?>
<interface>
  <object class="tk.Toplevel" id="mainwindow">
    <property name="height">200</property>
    <property name="resizable">both</property>
    <property name="title" translatable="yes">Minimal toplevel example</property>
    <property name="width">200</property>
    <child>
      <object class="ttk.Frame" id="container1">
        <property name="height">200</property>
        <property name="width">200</property>
        <layout>
          <property name="column">0</property>
          <property name="propagate">True</property>
          <property name="row">0</property>
          <property name="sticky">nsew</property>
          <columns>
            <column id="0">
              <property name="weight">1</property>
            </column>
          </columns>
          <rows>
            <row id="0">
              <property name="weight">1</property>
            </row>
          </rows>
        </layout>
        <child>
          <object class="ttk.Label" id="Label_1">
            <property name="anchor">center</property>
            <property name="font">{Helvetica} 36 {bold}</property>
            <property name="foreground">#000081</property>
            <property name="padding">40 10</property>
            <property name="text" translatable="yes">Hello World!</property>
            <layout>
              <property name="column">0</property>
              <property name="propagate">True</property>
              <property name="row">0</property>
              <property name="sticky">nsew</property>
            </layout>
          </object>
        </child>
      </object>
    </child>
  </object>
</interface>
#!/usr/bin/python
# File: toplevelminimal.py
import os
try:
    import tkinter as tk
except:
    import Tkinter as tk
import pygubu


CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))


class MyApplication:
    def __init__(self):
        #1: Create a builder
        self.builder = builder = pygubu.Builder()

        #2: Load an ui file
        builder.add_from_file(os.path.join(CURRENT_DIR, 'toplevelminimal.ui'))
        
        #3: Create the toplevel widget.
        self.mainwindow = builder.get_object('mainwindow')

    def quit(self, event=None):
        self.mainwindow.quit()

    def run(self):
        self.mainwindow.mainloop()
        
if __name__ == '__main__':
    app = MyApplication()
    app.run()
Clone this wiki locally