首页 > 解决方案 > Python和GTK3 - 手动设置按钮的最佳方式?

问题描述

我已经搜索过,但找不到关于如何做的很好的解释。

我已经构建了一个物理 MIDI(串行)控制台,以控制我在 python2.7(2.7 由于库..)和 Gtk3 中编写的 gui。

我可以控制刻度和切换按钮,但我不知道如何将按钮设置为按下并发出相关信号。

我知道我必须创建自己的信号“副本”然后发出它,但我不明白如何编写它。

标签: python-2.7signalsgtk3emit

解决方案


抱歉,您确实应该转换为 Python3。如果我没记错的话,今年年底,对 2.x 的支持将停止。

要“激活”切换按钮,请使用以下set_active方法:

tbtn = Gtk.ToggleButton("I'm toggleable")
tbtn.set_active(True)

在更改时,它将激活toggled按钮的信号。调用tbtn.get_active()以获取其状态。

顺便说一句,如果你想确保toggled被触发,你可能想先检查它的状态(之前.set_active)。

(将 Gtk 大写更改为与您使用的 Python 对应的值。我使用自省和 Gtk3)

编辑:

下面的代码采用 ToggleButton,并通过子类化并删除原始处理使其成为普通按钮(或多或少)。事实上,它不会发出切换信号,但这不会太难添加。

顶部按钮 (btn1) 是一个普通按钮,它会激活底部按钮。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  test_button_press.py
#
#  Copyright 2019 John Coppens <john@jcoppens.com>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
#


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

class My_button(Gtk.ToggleButton):
    def __init__(self, **kwargs):
        super(My_button, self).__init__(**kwargs)

        self.connect("button_press_event", self.on_btn2_press)
        self.connect("button_release_event", self.on_btn2_released)

    def on_btn2_press(self, btn, event):
        self.pressed2_at = event.time
        btn.set_active(True)
        return True

    def on_btn2_released(self, btn, event):
        print("Release2 after", event.time - self.pressed2_at)
        btn.set_active(False)
        return True


class MainWindow(Gtk.Window):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.connect("destroy", lambda x: Gtk.main_quit())

        self.btn1 = Gtk.Button("Button1")
        self.btn1.connect("clicked", self.on_btn1_clicked)

        self.btn2 = My_button(label = "Victim")

        self.vbox = Gtk.VBox(spacing = 4)
        self.vbox.pack_start(self.btn1, False, False, 0)
        self.vbox.pack_start(self.btn2, False, False, 0)

        self.add(self.vbox)
        self.show_all()


    def on_btn1_clicked(self, btn):
        self.btn2.set_active(True)


    def run(self):
        Gtk.main()


def main(args):
    mainwdw = MainWindow()
    mainwdw.run()

    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))

推荐阅读