the tkinter button does not work in ubuntu - class

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()

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

os.execl do not operating with classes

for the code below, execl destroy the script but not restart. If the method is out of the class is working. What I am doing wrong.?
import os
import sys
from tkinter import *
class parent():
def __init__(self,root):
self.root=root
def show_root(self):
self.root=Tk()
a=Button(self.root,text='restart',command=self.restart)
a.grid()
def restart(self):
sys.stdout.flush()
os.execl(sys.executable, 'python', __file__, *sys.argv[1:])
return
if __name__=='__main__':
gr=parent(None)
gr.show_root()

Application name appears broken in GNOME title bar

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)

Closing PySide2 application kills QProcess - not true with PyQt4

I have a simple test PyQt4 application where i'm using a QProcess to start a program (linux) and print the stdout. When I close the PyQt4 application the child process (started by QProcess) keeps running, which is what I want.
However when I run the same example using PySide2 instead (switching QtGui to QtWidgets etc) and I then close the PySide2 application, the child process also closes..
Is this a bug with either PyQt4 or PySide2? And is there a way to get PySide2 to have the same behaviour as PyQt4 in this case? I know there is startDetached on the QProcess but then I lose access to stdout so this isn't an option for me..
EDIT, added simple PySide2 example. In this case i'm opening Dolphin as the program - this isn't the program i'm opening in my real world application but it mimics the same behaviour
import sys
from PySide2 import QtWidgets,QtCore, QtWidgets
class gui(QtWidgets.QMainWindow):
def __init__(self):
super(gui, self).__init__()
self.initUI()
def stdoutReady(self, process):
data = str(self.process.readAllStandardOutput())
print('STDOUT: {}'.format(data))
def stderrorReady(self, process):
data = str(self.process.readAllStandardError())
print('STDERROR: {}'.format(data))
def processFinished(self, exitCode, exitStatus):
print('EXIT CODE: {}, EXIT STATUS: {}'.format(exitCode, exitStatus))
def initUI(self):
layout = QtWidgets.QHBoxLayout()
centralWidget = QtWidgets.QWidget()
centralWidget.setLayout(layout)
self.setCentralWidget(centralWidget)
self.process = QtCore.QProcess(self)
self.process.readyReadStandardOutput.connect(lambda: self.stdoutReady(self.process))
self.process.readyReadStandardError.connect(lambda: self.stderrorReady(self.process))
self.process.start('dolphin')
def main():
app = QtWidgets.QApplication(sys.argv)
ui=gui()
ui.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Spray cache for get service?

i am using cache headers like no-cache and no-store, i don´t know to do application level caching (maybe i could need some documentation here)
i print in console the data result when i call the method in mongodb, but it only works once after i run my app(that ocur in get service), the second time my app doesn´t print nothing, that is, it doesn't call the method.... that ocur when i try get a list of users the second time... for example, when i post something like insert new a user. i need to see the changes in the db in the frontend, my app seems get data from cache and it does´nt call the method to get the users again
the code I use in my spray scala service is
`package api
import spray.routing.Directives
import akka.actor.ActorRef
import spray.http.MediaTypes._
import core.UserRegister
import core.User
import scala.concurrent.ExecutionContext
import core.{User, LoginActor}
import akka.util.Timeout
import LoginActor._
import spray.http._
import scala.Some
import spray.json.JsonFormat
import spray.json.RootJsonFormat
import spray.json.JsArray
import spray.json.CollectionFormats
import spray.json._
import DefaultJsonProtocol._
import scala.util.parsing.json.JSONArray
import scala.util.parsing.json._
import data.UserDao
import core.UserListActor
import spray.routing.Route
import core.CoreActors
import spray.routing.HttpService
import core.Core
import akka.actor.{Props, ActorRefFactory, ActorSystem}
import akka.actor.ActorContext
import spray.routing.HttpServiceActor
import spray.http.HttpHeaders.RawHeader
import scala.concurrent.duration.Duration
import spray.routing.authentication.BasicAuth
import spray.routing.directives.CachingDirectives._
import spray.httpx.encoding._
import spray.caching._
import spray.caching.{LruCache, Cache}
import spray.caching.Cache
import web.StaticResources
import scala.concurrent.Future
class ListarUsuarioService(listaUsuario: ActorRef)(implicit executionContext: ExecutionContext)
extends Directives with DefaultJsonFormats with SprayCORSsupport with CORSSupport{
import akka.pattern.ask
import scala.concurrent.duration._
implicit val userFormat = jsonFormat2(User)
implicit val registerFormat = jsonFormat1(Register)
implicit val userRegisterFormat = jsonFormat5(UserRegister)
implicit val registeredFormat = jsonObjectFormat[Registered.type]
implicit val notRegisteredFormat = jsonObjectFormat[NotRegistered.type]
implicit val system = ActorSystem()
import system.dispatcher
lazy val simpleRouteCache = routeCache()
lazy val simpleCache = routeCache(maxCapacity = 5000, timeToIdle = 0.001 hour)
//lazy val cache = LruCache()
def routeCache(maxCapacity: Int = 2000, initialCapacity: Int = 100, timeToLive: Duration = 5 seconds,
timeToIdle: Duration = Duration.Inf): Cache[RouteResponse] =
LruCache(maxCapacity, initialCapacity, timeToLive, timeToIdle)
// and a Cache for its result type
val cache2: Cache[Double] = LruCache()
val listaUsuariosroute:Route =
cache(routeCache()){
cors{ addCORSDefaultSupport(){
path("usuario") {
get {
respondWithMediaType(`application/json`) {
_.complete {
//Elemento de la lista
//listaUsuarios(1)
UserListActor.listaUsuarios.toJson.convertTo[JsArray].prettyPrint }
}
}
}
}
}
}//cors
}
`
I am using Cors and cache headers like no-store, public and no-cache, but it doesn´t works, even i clear my cache browser but it neither works