GTK3 / Glib 重复一个函数

GTK3 / Glib Repeating A Function

我需要 运行 一个 Python 函数,通过使用没有 freezing/interupting GTK3 GUI 的 GLib。 GLib.timeout_add(millisecond, function_name) 是不够的。我的代码需要更多控制。但是它会给出警告,并且当使用以下代码时它不会每隔几秒重复一次该功能:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib

builder = Gtk.Builder()
builder.add_from_file('test1.ui')
window1 = builder.get_object('window1')

class Signals:
    def on_window1_destroy(self, widget):
        Gtk.main_quit()

builder.connect_signals(Signals())

def function1():
    print("1")
    global source1
    source1 = GLib.timeout_source_new(1000)
    source1.set_callback(function1)
    context1 = GLib.MainContext.default()
    source1.attach(context1)

function1()

window1.show_all()
Gtk.main()

警告:

TypeError: function1() takes 0 positional arguments but 1 was given

但是下面的代码在没有警告的情况下运行并且函数每隔几秒重复一次:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib

builder = Gtk.Builder()
builder.add_from_file('test1.ui')
window1 = builder.get_object('window1')

class Signals:
    def on_window1_destroy(self, widget):
        Gtk.main_quit()

builder.connect_signals(Signals())

def function1(var1):
    print("1")
    global source1
    source1 = GLib.timeout_source_new(1000)
    source1.set_callback(function1)
    context1 = GLib.MainContext.default()
    source1.attach(context1)

function1(1)

window1.show_all()
Gtk.main()

这是简单的 GUI 文件 (test1.ui):

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.38.2 -->
<interface>
  <requires lib="gtk+" version="3.20"/>
  <object class="GtkWindow" id="window1">
    <property name="can-focus">False</property>
    <property name="border-width">10</property>
    <property name="default-width">200</property>
    <property name="default-height">200</property>
    <property name="icon-name">system-monitoring-center</property>
    <child>
      <placeholder/>
    </child>
  </object>
</interface>

我的函数不需要 var1。在这里可以做什么? 这是文档,但我无法解决问题: GLib.Source

OS: Debian-like Linux, Python 3.9, GTK 3.24

要修复此错误,只需将 *args 添加到 function1 的参数中:def function1(*args)::

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib

builder = Gtk.Builder()
builder.add_from_file('/home/sam/programs/python/testing/SO/test1.ui')
window1 = builder.get_object('window1')

class Signals:
    def on_window1_destroy(self, widget):
        Gtk.main_quit()

builder.connect_signals(Signals())

def function1(*args): # Added *args
    print("1")
    global source1
    source1 = GLib.timeout_source_new(1000)
    source1.set_callback(function1)
    context1 = GLib.MainContext.default()
    source1.attach(context1)

function1()

window1.show_all()
Gtk.main()

* 告诉 python 将任何位置参数放入元组中,在本例中为 args。如果您 print(args)function1() 内,您应该会看到类似 (None,) 的内容。最好的部分是,无论是否将参数传递给 function1(),使用 *args 都有效!