I have a problem in a simple Glade/Gtk project, I have some objects like Button, Text inputs etc. I have a basic error, gi.repository.Gtk has no attribute 'builder'. Any Ideas? Thanks in advance
Here's the error that I receive (https://imgur.com/a/14cEdn0)
import gi
gi.require_version('Gtk', '3.0')
import gi.repository
from gi.repository import Gtk
class Main:
def __init__(self):
gladeFile = Gtk.builder
self.builder = Gtk.Builder()
self.builder.add_from_file(gladeFile)
self.builder.connect_signals(self)
window = self.builder.get_object("button1")
window.show()
if __name__ == '__main__':
main = Main()
Gtk.main()
Looks like your gladeFile should be a string containing the path to your glade file, e.g. gladeFile = "example.glade".
Related
How can mpv render to GTK4 window or widget?
In GTK3 it was quite easy to get XID (and put it as argument to MPV) but in GTK4 It seem have to be done with GtkX11 and X11Surface https://docs.gtk.org/gdk4-x11/method.X11Surface.get_xid.html
But I have not clue how to do that in python - can't get surface from window/widget.
#!/usr/bin/env python3
import gi
import mpv
gi.require_version('Gtk', '4.0')
gi.require_version('Gdk', '4.0')
gi.require_version('GdkX11', '4.0')
from gi.repository import Gtk, Gdk, GdkX11
class MainClass(Gtk.ApplicationWindow):
def __init__(self, app):
super(MainClass, self).__init__()
self.set_application(app)
self.set_default_size(600, 400)
self.connect("destroy", self.on_destroy)
widget = Gtk.Frame()
self.set_child(widget)
self.present()
# Can't get XID from widget there
self.mpv = mpv.MPV(wid=str(GdkX11.X11Surface.get_xid(widget)))
self.mpv.play("test.webm")
def on_destroy(self, widget, data=None):
self.mpv.terminate()
Gtk.main_quit()
def on_activate(app):
application = MainClass(app)
if __name__ == '__main__':
# This is necessary since like Qt, Gtk stomps over the locale settings needed by libmpv.
# Like with Qt, this needs to happen after importing Gtk but before creating the first mpv.MPV instance.
import locale
locale.setlocale(locale.LC_NUMERIC, 'C')
app = Gtk.Application()
app.connect('activate', on_activate)
app.run(None)
TypeError: argument self: Expected GdkX11.X11Surface, but got gi.repository.Gtk.Frame
I don't know if this is completely correct
GdkX11.X11Surface.get_xid() takes a X11Surface as a parameter
Try this:
self.mpv = mpv.MPV(wid=str(GdkX11.X11Surface.get_xid(self.get_surface())))
This worked for me
I'm trying to create a simple AppIndicator with Python.
The code is pretty similar with:
import gi
from gi.repository import Gtk
from gi.repository import AppIndicator3 as appindicator
APPINDICATOR_ID = 'myapp'
def main():
indicator = appindicator.Indicator.new(APPINDICATOR_ID, '/usr/share/myapp/images/icon.svg', appindicator.IndicatorCategory.SYSTEM_SERVICES)
indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
Gtk.main()
It works very well, but I would like to introduce an animated icon. A blinking icon for example.
Not a static one.
I tried to convert the SVG file to GIF, but it does not work as well.
Is there a way to create a GdkPixbuf.PixbufAnimation (example) within AppIndicator3?
If yes, How can I do it?
I don't know if my answer will work for you but I see you are only importing libraries, assigning a variable, and defining some code. You may want to have the main(): code loop by typing:
This will give you the option to add return True or return False:
import gi
from gi.repository import Gtk
from gi.repository import AppIndicator3 as appindicator
APPINDICATOR_ID = 'myapp'
def main():
indicator = appindicator.Indicator.new(APPINDICATOR_ID, '/usr/share/myapp/images/icon.svg', appindicator.IndicatorCategory.SYSTEM_SERVICES)
indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
Gtk.main()
while main():
pass
Or if you want the code to keep going until you click the stop button:
import gi
from gi.repository import Gtk
from gi.repository import AppIndicator3 as appindicator
APPINDICATOR_ID = 'myapp'
def main():
indicator = appindicator.Indicator.new(APPINDICATOR_ID, '/usr/share/myapp/images/icon.svg', appindicator.IndicatorCategory.SYSTEM_SERVICES)
indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
Gtk.main()
main()
I found a workaround for this. Specially, if you are trying to configure a GIF.
For me, create a manual GIF worked. This solution requires a better approach related to concurrency but the prototype is here:
import gi
import time
import signal
import threading
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, GLib
from gi.repository import AppIndicator3 as appindicator
APPINDICATOR_ID = 'myapp'
finished = False
def change_icon(indicator, index=5):
indicator.set_icon("spinner-%s.svg" % str(index))
def render_icon(indicator):
i = 0
while True:
# I have 10 SVG images
index = (i % 10)
GLib.idle_add(change_icon, indicator, index)
time.sleep(0.5)
if finished:
break
i += 1
def on_click(widget):
global finished
finished = True
Gtk.main_quit()
def main():
indicator = appindicator.Indicator.new(APPINDICATOR_ID, 'spinner-0.svg', appindicator.IndicatorCategory.SYSTEM_SERVICES)
indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
menu = Gtk.Menu()
quit = Gtk.MenuItem('Quit')
quit.connect('activate', on_click)
menu.append(quit)
menu.show_all()
indicator.set_menu(menu)
thread = threading.Thread(target=render_icon, args=(indicator,))
thread.daemon = True
thread.start()
signal.signal(signal.SIGINT, signal.SIG_DFL)
Gtk.main()
main()
I created a spinner with 10 different frames and I can iterate using a Thread and set_icon + GLib.iddle_add().
Again, it requires a better solution in terms of Thread concorrency, but it works as a starting point.
I'm working on a gtk3 front end for libvlc written in python using python-vlc. I'm following the gtk3 example from the python-vlc github page, but am experiencing strange behavior. I have a widget that looks like that:
import gi
import sys
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class PlayerWidget(Gtk.DrawingArea):
__gtype_name__ = 'VLCWidget'
def __init__(self, instance):
Gtk.DrawingArea.__init__(self)
self.player = instance.media_player_new()
def handle_embed(*args):
if sys.platform == 'win32':
self.player.set_hwnd(self.get_window().get_handle())
else:
self.player.set_xwindow(self.get_window().get_xid())
return True
self.connect("realize", handle_embed)
self.set_size_request(320, 200)
I embed it here:
import vlc
import sys
from widgets.player import PlayerWidget
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class VideoPlayer(Gtk.Window):
CONST_APP_NAME = "video player"
def __init__(self):
Gtk.Window.__init__(self)
if 'linux' in sys.platform:
self.instance = vlc.Instance("--no-xlib")
else:
self.instance = vlc.Instance()
self.set_default_size(800, 600)
header = Gtk.HeaderBar(title=self.CONST_APP_NAME)
header.set_subtitle("Filename.mp4")
header.set_show_close_button(True) # this one is the troublemaker
self.set_titlebar(header)
self.connect("destroy", Gtk.main_quit)
self.player_widget = PlayerWidget(self.instance)
self.add(self.player_widget)
def show_window(self):
self.show_all()
Gtk.main()
def set_media(self, fname):
self.player_widget.player.set_media(self.instance.media_new(fname))
def play(self):
self.player_widget.play()
if not len(sys.argv) > 0:
print('Please provide a filename')
sys.exit(1)
p = VideoPlayer()
p.set_media(sys.argv[1])
p.play()
p.show_window()
p.instance.release()
It works fine if I embed it into an empty Gtk.window. If, however, I add a HeaderBar to that window as well and then add a close button to that HeaderBar using set_show_close_button(True) it stops working as expected. The PlayerWidget will not be shown embedded anymore, but instead a new (second) window will be opened where the video is played. If I do not add the close button to the HeaderBar the widget gets embedded just fine.
A warning is thrown to the console: xcb_window window error: X server failure
I first thought it could be because I use gnome under wayland, but it occurs on X as well as on wayland.
Any help is appreciated.
Update 1: Added full code example. When I ran it today, the first time it actually worked as expected, but after that the same bug as described above occured again. Very weird.
As #mtz and #stovfl correctly pointed out, the problem was that I started the video playback (p.play()) before creating the window (p.show_window()).
As suggested I used GLib.idle_add(p.play) to let the window start the playback once it's ready. The GLib module can be imported using from gi.repository import GLib.
I am writing an app-indicator on Ubuntu 18.04. Getting started was the most difficult part. Docs don't help much. I found this blog and I have a POC that just shows a fixed text on my application bar like this -
What I have not been able to figure out is how to update this text periodically or dynamically to display actual information that I need for example: CPU frequency, temperature etc.
I have looked at the following places, however I think i am missing something.
https://lazka.github.io/pgi-docs/Gtk-3.0/classes/Label.html
https://askubuntu.com/questions/108035/writing-indicators-with-python-gir-and-gtk3
https://lazka.github.io/pgi-docs/AppIndicator3-0.1/classes/Indicator.html#AppIndicator3.Indicator.set_label
The working code that I have is -
import os
import signal
from gi.repository import Gtk as gtk
from gi.repository import AppIndicator3 as appindicator
APPINDICATOR_ID = 'myappindicator'
def main():
indicator = appindicator.Indicator.new(APPINDICATOR_ID, gtk.STOCK_INFO, appindicator.IndicatorCategory.SYSTEM_SERVICES)
indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
indicator.set_menu(build_menu())
indicator.set_label('world', '8.8')
gtk.main()
def build_label():
label = gtk.Label()
return label
def build_menu():
menu = gtk.Menu()
item_quit = gtk.MenuItem('Quit')
item_quit.connect('activate', quit)
menu.append(item_quit)
menu.show_all()
return menu
def quit(source):
gtk.main_quit()
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal.SIG_DFL)
main()
EDIT:
Referring to this similar SO post, and this apparently working example, I tried adding timeout_add_seconds, and timeout_add however the text doesn't change at all, it displays only the first call. I inserted a print statement there too, and surprisingly, that also prints only once. Don't know why that is happening -
New code attempt-
import random
from gi.repository import Gtk, GLib
from gi.repository import AppIndicator3 as appindicator
APPINDICATOR_ID = 'myappindicator'
def cb_exit(w, data):
Gtk.main_quit()
def change_label(ind_app):
text = 'Hello World, what a great day'.split()
t = random.choice(text)
print(t)
ind_app.set_label(t , '')
ind_app = appindicator.Indicator.new(APPINDICATOR_ID, Gtk.STOCK_INFO, appindicator.IndicatorCategory.SYSTEM_SERVICES)
ind_app.set_status(appindicator.IndicatorStatus.ACTIVE)
# create a menu
menu = Gtk.Menu()
menu_items = Gtk.MenuItem("Exit")
menu.append(menu_items)
menu_items.connect("activate", cb_exit, '')
menu_items.show_all()
ind_app.set_menu(menu)
GLib.timeout_add(1000, change_label, ind_app)
Gtk.main()
I figured this out myself. I was using the timeout_add function incorrectly. The called function must return anything non false for the timer to continue. In my case it is returning nothing, hence the timer was destroying itself. The docs here and this SO post helped me figure this out. SO the code finally looks like this -
import random
from gi.repository import Gtk, GLib
from gi.repository import AppIndicator3 as appindicator
APPINDICATOR_ID = 'myappindicator'
def change_label(ind_app):
text = 'Hello world, what a beautiful day'.split()
t = random.choice(text)
print(t)
ind_app.set_label(t , '')
return True
def quit(source):
Gtk.main_quit()
ind_app = appindicator.Indicator.new(APPINDICATOR_ID, Gtk.STOCK_INFO, appindicator.IndicatorCategory.SYSTEM_SERVICES)
ind_app.set_status(appindicator.IndicatorStatus.ACTIVE)
# create a menu
menu = Gtk.Menu()
menu_items = Gtk.MenuItem("Exit")
menu.append(menu_items)
menu_items.connect("activate", quit)
menu_items.show_all()
ind_app.set_menu(menu)
GLib.timeout_add(1000, change_label, ind_app)
Gtk.main()
Env - python2.7, gstreamer 1.0 on windows7
I was trying to run codes from http://bazaar.launchpad.net/~jderose/+junk/gst-examples/view/head:/video-player-1.0 on my env, and it's failing with AttributeError: 'gtk.gdk.Win32Window' object has no attribute 'get_xid'
I found minimum code to test get_xid and pasting it here:-
import gi
gi.require_version("GdkX11", "3.0")
gi.require_version('Gtk', '3.0')
from gi.repository import GdkX11, Gtk, GstVideo
class App:
def __init__(self):
win = Gtk.Window()
win.resize(400, 400)
win.connect('delete-event', Gtk.main_quit)
da = Gtk.DrawingArea()
win.add(da)
win.show_all()
import pdb;pdb.set_trace()
print da.get_property('window').get_xid()
if __name__ == "__main__":
App()
Gtk.main()
AttributeError: 'gtk.gdk.Win32Window' object has no attribute 'get_xid'
Ideally if i have imported GdkX11 then window object should have get_xid, But its not working on windows7 environment, looks like GdkX11 is not for windows user. Please suggest me how should I solve this issue.
On Windows machines, get_xid() will cause the issue you are seeing.
A workaround is provided in the following answer: Get the window handle in PyGI