【发布时间】:2021-10-12 22:49:24
【问题描述】:
我有一个 Python3 程序,可以改变我系统的音量。我想要的行为是它就像一个弹出窗口,它会在窗口之后自行销毁,首先获得焦点,然后失去焦点。
我的代码有两个问题。第一个,失去焦点时它不会自行关闭,给我一个错误:
on_focus_out_event() takes 2 positional arguments, but 3 were given.
然而,即使解决了这个错误,它也无法实现我想要的行为。
这是我第一个用 Python 编写的程序,不幸的是,我需要一个密切的帮助。如果有人可以帮助我,我将不胜感激。
#!/usr/bin/python3
import sys
import subprocess
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class AppWindow(Gtk.ApplicationWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_border_width(0)
self.set_size_request(500, -1)
scale_float = Gtk.Scale.new_with_range(Gtk.Orientation.HORIZONTAL, 0.0, 153, 1.0)
scale_float.set_value_pos(Gtk.PositionType.LEFT)
scale_float.connect('value-changed', self.on_value_changed)
scale_float.show_all()
label_box = Gtk.Box()
label_box.pack_start(
Gtk.Image.new_from_icon_name('audio-volume-high', 1), False, False,5)
label_box.pack_start(Gtk.Label(label=''), True, True, 0)
label_box.show_all()
notebook = Gtk.Notebook()
notebook.append_page(scale_float, label_box)
notebook.set_tab_pos(Gtk.PositionType.RIGHT)
self.connect('focus-out-event', self.on_focus_out_event)
self.add(notebook)
self.show_all()
def on_value_changed(self, scale_float):
val = int(scale_float.get_value())
proc = subprocess.Popen('pactl set-sink-volume 0 ' + str(val) + '%', shell=True, stdout=subprocess.PIPE)
proc.wait()
def on_focus_out_event(self, event):
self.destroy()
class Application(Gtk.Application):
def __init__(self, *args, **kwargs):
super().__init__(*args, application_id="org.example.volume_control",**kwargs)
self.window = None
def do_activate(self):
if not self.window:
self.window = AppWindow(application=self,title="")
self.window.show_all()
self.window.present()
if __name__ == "__main__":
app = Application()
app.run(sys.argv)
【问题讨论】:
标签: python-3.x gtk3 pygtk