linux中的pythonGtk GUI 编程

时间:2021-12-23 01:15:16

安装:

$sudo apt install libgtk3*

$sudo apt install glade

然后打开glade进行设计。

ui.glade

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.20.0 -->
<interface>
<requires lib="gtk+" version="3.0"/>
<object class="GtkWindow" id="window">
<property name="can_focus">False</property>
<signal name="delete-event" handler="onDeleteWindow" swapped="no"/>
<child>
<object class="GtkGrid">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkButton" id="button">
<property name="label" translatable="yes">click me</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<signal name="clicked" handler="clicked" object="label" swapped="yes"/>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<placeholder/>
</child>
</object>
</child>
</object>
</interface>

app.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import gi
import time
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
    class Application(Gtk.Window):
        def onDeleteWindow(self, *args):
            Gtk.main_quit(*args)
        def clicked(self, button):
            print("Hello World!")
            self.window.set_title("clicked")
            self.button.set_label("clicked")
        def __init__(self):
            builder = Gtk.Builder()
            builder.add_from_file("ui.glade")
            self.window = builder.get_object("window")
            self.window.connect("delete-event", self.onDeleteWindow)
            self.button=builder.get_object("button")
            self.button.connect("clicked",self.clicked)
            def show_all(self):
            self.window.show_all()
app = Application()
app.show_all()
Gtk.main()

linux中的pythonGtk GUI 编程

运行时的效果

linux中的pythonGtk GUI 编程

点击后的效果

其中红色部分是关键。