Application name appears broken in GNOME title bar - gtk

I am trying to write applications with PyGObject. I have set the app name using GLib but it seems to be broken. There is no problem with other system programs that use Turkish characters in their titles.
import sys
import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
from gi.repository import Gtk, Adw, GLib
class MainWindow(Gtk.ApplicationWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_default_size(300, 400)
self.set_title("Merhaba dünya!")
GLib.set_application_name("Merhaba Dünya!")
GLib.set_prgname('Merhaba Dünya!')
self.main_box = Gtk.Box(
orientation = Gtk.Orientation.VERTICAL
)
self.set_child(self.main_box)
self.lbl_hello = Gtk.Label(
label = "Merhaba dünya"
)
self.main_box.append(self.lbl_hello)
self.btn_hello = Gtk.Button(
label = "Bana tıkla"
)
self.btn_hello.connect(
"clicked",
self.btn_hello_clicked
)
self.main_box.append(self.btn_hello)
def btn_hello_clicked(self, button):
print("Merhaba dünya!")
class MyApp(Adw.Application):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.connect('activate', self.on_activate)
def on_activate(self, app):
self.win = MainWindow(application=app)
self.win.present()
app = MyApp(application_id="net.teteos.example")
app.run(sys.argv)

Related

Dialog button click in test not dismissing dialog PyQt5/pytest

When running a test that launches a dialog, the test is unable to programmatically click a button on the dialog. If I manually click the button, the test completes. Also I'm unsure why the dialog even shows at all (since I don't see the original window it was launched from).
Python 3.7.16, pytest 7.2.1
foo.py
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Foo(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setupUi()
def setupUi(self):
self.resize(400, 200)
self.button = QtWidgets.QPushButton("ClickMe")
self.button.clicked.connect(self.launchDialog)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.button)
self.setLayout(layout)
def launchDialog(self):
self.dialog = FooDialog(parent=self)
self.dialog.exec()
class FooDialog(QtWidgets.QMessageBox):
def __init__(self, parent=None):
super(FooDialog, self).__init__(parent)
self.setWindowTitle("foo.FooDialog")
self.button = QtWidgets.QPushButton("ClickMe")
self.addButton(self.button, QtWidgets.QMessageBox.ButtonRole.ActionRole)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
foo = Foo()
foo.show()
sys.exit(app.exec_())
test_foo.py
import pytest, time
from pytestqt.qtbot import QtBot
from PyQt5 import QtCore
from foo import Foo
#pytest.fixture
def app(qtbot):
foo = Foo()
qtbot.addWidget(foo)
return foo
def test_button(app):
qtbot = QtBot(app)
qtbot.mouseClick(app.button, QtCore.Qt.MouseButton.LeftButton, delay=0)
time.sleep(2)
qtbot.mouseClick(app.dialog.button, QtCore.Qt.MouseButton.LeftButton, delay=0)
I run the test thus:
pytest -s test_foo.py
I ran the test and expected it to complete, but instead the test hangs waiting for the button on the dialog to be clicked.
I worked around the problem by mocking the dialog

promoted classes inherintance

How can I get access to GUI resoures, for example labelroi after conforming the roi image pixmap in class Labella...if self.ui.labelroi.setPixmap(roi image) or Principal.labelroi.setPixmap(roi image) get an error, and I'm not really clear in classes instantiation mecanism...
Another question: how could be the mouse release event, triggered into Labella 'heared' from Principal?
GUI
In MainWindow class:
labelimage: show image
labelroi: show defined roi in image
pushButtonexp: explores dir
Main Program
import sys
sys.path.append("../cursoqt/sample_editor")
from PyQt5.QtWidgets import QApplication, QFileDialog, QMainWindow
from PyQt5.QtGui import QImage, QPixmap, QPainter, QPen, QGuiApplication
from PyQt5.QtCore import Qt
from paint_rectangle import * # GUI generated by pyqt designer
from labella import * # Qlabel promoted class
class Principal(QMainWindow):
file_name = ''
def __init__(self):
super().__init__()
self.roi = QtCore.QRect()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.pushButtonexp.clicked.connect(self.openFile)
self.show()
def openFile(self):
file_name, _ = QFileDialog.getOpenFileName(self, 'Open file', '/home', "Images (*.png *.jpg)")
if file_name != '':
img_pixmap = Labella.convertPixmap(self, file_name)
self.displayImg(img_pixmap)
else:
self.ui.labelimage.deleteRect()
def displayImg(self, pixmap):
if pixmap.isNull():
self.ui.labelimage.clear()
self.ui.labelimage.deleteRect()
else:
self.ui.labelimage.deleteRect()
self.ui.labelimage.setPixmap(pixmap)
self.ui.labelimage.setCursor(Qt.CrossCursor)
if __name__=='__main__':
app = QApplication(sys.argv)
window = Principal()
window.show()
sys.exit(app.exec_())
Qlabel promoted class
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QFileDialog
from paint_rectangle import * # GUI generated by pyqt designer
from call_paint_rectangle import * # Main class
class Labella(QtWidgets.QLabel):
file_n = ''
def __init__(self, parent):
super().__init__(parent=parent)
self.drawing_flg = False
self.ini_coord = QtCore.QPoint()
self.fin_coord = QtCore.QPoint()
self.exist_img_flg = 0
self.rect_roi = QtCore.QRect()
def convertPixmap(self,fileN):
Labella.file_n = fileN
pixmapformat = QPixmap(Labella.file_n)
return pixmapformat
def verifyPixmap(self):
if self.pixmap():
self.exist_img_flg = 1
else:
self.exist_img_flg = 0
def deleteRect(self):
if self.rect_roi:
self.ini_coord = self.fin_coord = QtCore.QPoint()
self.update()
def paintEvent(self, event):
super().paintEvent(event)
qp = QtGui.QPainter(self)
qp.setPen(QtGui.QPen(QtCore.Qt.red,1,QtCore.Qt.SolidLine))
if self.ini_coord and self.fin_coord and self.exist_img_flg == 1:
self.rect_roi = QtCore.QRect(self.ini_coord, self.fin_coord)
qp.drawRect(self.rect_roi)
def mousePressEvent(self, event):
# verifyPixmap verifies if there's a pixmap in qlabel
self.verifyPixmap()
if event.button() == QtCore.Qt.LeftButton and self.exist_img_flg == 1:
self.drawing_flg = True
self.ini_coord = self.fin_coord = event.pos()
elif self.exist_img_flg == 0:
self.drawing_flg = False
def mouseMoveEvent(self, event):
if self.drawing_flg:
self.fin_coord = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if self.drawing_flg:
self.drawing_flg = False
self.update()
r_img = self.createMappedROI()
self.ui.labelroi.setPixmap(r_img) # HERE OCCURS THE ERROR LABELLA HAVE NOT ATTRIBUTE UI
def createMappedROI(self):
pixmap_size_Rect = self.pixmap().rect()
contents_label_Rect = QtCore.QRectF(self.contentsRect())
width_rate = pixmap_size_Rect.width()/contents_label_Rect.width()
height_rate = pixmap_size_Rect.height()/contents_label_Rect.height()
mapped_roi = QtCore.QRect(int(self.rect_roi.x() * width_rate), int(self.rect_roi.y() * height_rate),
int(self.rect_roi.width() * width_rate), int(self.rect_roi.height() * height_rate))
self.qimage = QImage()
self.qimage.load(Labella.file_n)
crop_image = self.qimage.copy(mapped_roi)
roi_image = QPixmap.fromImage(crop_image)
return roi_image

the tkinter button does not work in ubuntu

I can't make the button work, it works as it should on the windows, why doesn't it work in ubuntu?
import tkinter as tk
from tkinter import ttk
import sys
class Application(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.attributes("-alpha", 1)
self.attributes("-topmost", True)
self.overrideredirect(True)
self.resizable(False, False)
self.title("CPU-RAM usage monitor bar")
self.set_ui()
def set_ui(self):
exit_but = tk.Button(self, text="Exit", command=lambda: self.app_exit)
exit_but.pack(fill=tk.X)
def app_exit(self):
self.destroy()
sys.exit()
root = Application()
root.mainloop()

pytest - mockup a complex module import

I have found several posts on how to "hide" a package and simulate an ImportError with pytest, however, I haven't succeeded in my case and I am looking for some help:
Test for import of optional dependencies in __init__.py with pytest: Python 3.5 /3.6 differs in behaviour
Test behavior of code if optional module is not installed
and related
Here is the content of an __about__.py file that I want to test with pytest.
"""Get the metadata from the package or from setup.py."""
try:
import importlib
metadata = importlib.metadata
except ImportError:
import importlib_metadata as metadata
try:
data = metadata.metadata("mypackage")
__version__ = data["Version"]
__author__ = data["Author"]
__name__ = data["Name"]
except metadata.PackageNotFoundError:
# The repo of the package is accessible to python to get at least the version
import re
from pathlib import Path
try:
from nested_grid_plotter import __file__ as loc
with open(Path(loc).parent.joinpath("../setup.py"), "r") as f:
data = f.read()
except FileNotFoundError:
data = ""
def version_parser(v):
"""Parse the version from the setup file."""
version_pattern = (
r"""(version\s*=\s*)["|'](\d+(=?\.(\d+(=?\.(\d+)*)*)*)*)["|']"""
)
regex_matcher = re.compile(version_pattern).search(v)
if regex_matcher is None:
return "unknwon"
return regex_matcher.group(2)
try:
__version__ = version_parser(data)
except Exception:
__version__ = "unknown"
__author__ = "unknown"
__name__ = "unknown"
Here is the __init__.py at the root of the package:
from .__about__ import __version__, __name__, __author__
And here is the tests that I have come up with until now. However, I am not able to hide importlib.
"""Test the file __about__.py."""
import pytest
import sys
class PackageDiscarder:
def __init__(self):
self.pkgnames = []
def find_spec(self, fullname, path, target=None):
if fullname in self.pkgnames:
raise ImportError()
#pytest.fixture
def no_requests():
sys.modules.pop("importlib", None)
d = PackageDiscarder()
d.pkgnames.append("importlib")
sys.meta_path.insert(0, d)
yield
sys.meta_path.remove(d)
#pytest.fixture(autouse=True)
def cleanup_imports():
yield
sys.modules.pop("mypackage", None)
def test_requests_available():
import mypackage
assert mypackage.__version__ != "unknwon"
#pytest.mark.usefixtures("no_requests")
def test_requests_missing():
import mypackage
assert mypackage.__version__ != "unknwon"
Here is the coverage report:
Name Stmts Miss Cover Missing
----------------------------------------------------------------
mypackage/__about__.py 31 10 68% 5-6, 10-12, 23-24, 33, 38-39
----------------------------------------------------------------
TOTAL 31 10 68%

Implementing "gravity" Effect

Currently I am trying to make a game with a horse that jumps obstacles that come at it, and I am currently working on the horse animation. I can get the horse to jump up, but I am still failing on implementing "gravity" and making the horse come back to the ground after it jumps.
Here's my current code:
import pyglet
import time
# background_sound = pyglet.media.load(
# 'Documents/Leave The Night On.mp3',
# streaming=False)
class horse(pyglet.sprite.Sprite):
def __init__(self, batch):
self._img_main = pyglet.image.load("sihorseav.png")
self.img_right1 = pyglet.image.load("sihorseav.png")
self.img_right2 = pyglet.image.load("sihorseav.png")
self.anim_right = pyglet.image.Animation.from_image_sequence([self.img_right1, self.img_right2], 0.5, True)
pyglet.sprite.Sprite.__init__(self, self._img_main)
self.time = 0
def forward_movement(self, flag=True):
if keymap[pyglet.window.key.UP]:
self.horse.time = time.time()
self.horse.jump()
def jump(self):
print time.time()-self.time
self.y -= -200 +20**(time.time()-self.time+.2)
class Window(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
self.batch = pyglet.graphics.Batch()
self.label = pyglet.text.Label(text="Score: 0", x=850, y=650, batch=self.batch)
image = pyglet.resource.image('sibackground.jpg')
self.background = pyglet.sprite.Sprite(image, batch=self.batch)
self.player = horse(batch = self.batch)
self.keys_held = []
def on_key_press(self, symbol, modifiers):
self.keys_held.append(symbol)
if symbol == pyglet.window.key.UP:
self.player.time=time.time()
self.player.jump()
def on_draw(self):
self.clear()
self.batch.draw()
self.player.draw()
self.label.draw()
def main():
window = Window(width=960, height=700, caption='Pyglet')
pyglet.app.run()
if __name__ == '__main__':
main()