How to show image in PyQT GUI? - image

I want to show an Image in GUI using filepicker in PyQT. So far I managed to open image files, but completely confused on how to show image in GUI.
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(100, 100, 500, 300)
self.setWindowTitle("PyQT Show Image")
openFile = QtGui.QAction("&File", self)
openFile.setShortcut("Ctrl+O")
openFile.setStatusTip("Open File")
openFile.triggered.connect(self.file_open)
self.statusBar()
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('&File')
fileMenu.addAction(openFile)
self.home()
def home(self):
self.show()
def file_open(self):
name = QtGui.QFileDialog.getOpenFileName(self, 'Open File')
file = open(name, 'r')
def run():
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
run()
Kindly guide me here on how to show image in GUI. Thank you

How about this?
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(100, 100, 500, 300)
self.setWindowTitle("PyQT Show Image")
openFile = QtGui.QAction("&File", self)
openFile.setShortcut("Ctrl+O")
openFile.setStatusTip("Open File")
openFile.triggered.connect(self.file_open)
self.statusBar()
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('&File')
fileMenu.addAction(openFile)
self.lbl = QtGui.QLabel(self)
self.setCentralWidget(self.lbl)
self.home()
def home(self):
self.show()
def file_open(self):
name = QtGui.QFileDialog.getOpenFileName(self, 'Open File')
pixmap = QtGui.QPixmap(name)
self.lbl.setPixmap(pixmap.scaled(self.lbl.size()))
def run():
app = QtGui.QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
run()

I have updated the code in accordance with pyQt5 as it can be helpful for some persons.(reference : Controlix's code posted above)
import sys
from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import QFileDialog,QLabel,QAction,QMainWindow,QApplication
class Window(QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(100, 100, 500, 300)
self.setWindowTitle("PyQT Show Image")
openFile = QAction("&File", self)
openFile.setShortcut("Ctrl+O")
openFile.setStatusTip("Open File")
openFile.triggered.connect(self.file_open)
self.statusBar()
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('&File')
fileMenu.addAction(openFile)
self.lbl = QLabel(self)
self.setCentralWidget(self.lbl)
self.home()
def home(self):
self.show()
def file_open(self):
name = QFileDialog.getOpenFileName(self, 'Open File')
print(name)
pixmap = QtGui.QPixmap(name[0])
self.lbl.setPixmap(pixmap.scaled(self.lbl.size()))
def run():
app = QApplication(sys.argv)
GUI = Window()
sys.exit(app.exec_())
run()

Related

how can I solve this error "Exception has occurred: TypeError module() takes at most 2 arguments (3 given)"

class Anime(commands.cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def anime(ctx, self, *, query):
try:
anime = animec.anime(query)
except:
await ctx.send(embed=discord.Embed(description="Anime not found", color=discord.Color.blue()))
return
embed = discord.Embed(title=anime.title_english, url=anime.url, description=f"{anime.description[:200]}...",
color=discord.Color.red())
embed.add_field(name="Episodes", value=str(anime.episodes))
embed.add_field(name="Rating", value=str(anime.rating))
embed.add_field(name="Genre", value=str(anime.genres))
embed.add_field(name="Broadcast", value=str(anime.broadcast))
embed.ser_thumbmail(url=anime.poster)
await ctx.send(embed=embed)

grpc error ...No handlers could be found for logger "grpc._common"

I am just getting a hang of grpc and tried to build a custom client-server procedure where the client sends an id and a name corresponding to the id.
Here is the custom.proto file:
syntax = "proto3" ;
// Interface exported by the server
service Detail {
rpc GetName(idx) returns (namex) {}
}
message idx {
int32 id = 1;
}
message namex{
int32 id = 1;
string name = 2;
}
From this proto file custom_pb2 and custom_pb2_grpc.py are generated.
This is the custom_db.json
[{"id": 0, "name":"kiran"},
{"id":1, "name":"kirthana"},
{"id":2, "name":"kishore"}
]
This is custom_resources.py
import json
import custom_pb2
def read_custom_database():
''' Reads the custom database I created.'''
names_list = []
with open("custom_db.json") as custom_db_file:
for item in json.load(custom_db_file):
itemx = custom_pb2.namex(id=item["id"], name=item["name"])
names_list.append(itemx)
return names_list
This is the custom_server.py
import custom_pb2_grpc
import custom_resources
import time
_ONE_DAT_IN_SECONDS = 60*60*24
def get_name(custom_db,idx):
'''Returns name of a given id or none'''
for namex in custom_db:
if namex.id == idx:
return namex.name
return None
class DetailServicer(custom_pb2_grpc.DetailServicer):
"""Provides methods that implements the custom server."""
def __init__(self):
self.db = custom_resources.read_custom_database()
def GetName(self, request, context):
name = get_name(self.db, request)
if name is None:
return "Not Found"
else:
return name
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
custom_pb2_grpc.add_DetailServicer_to_server(DetailServicer(), server)
server.add_insecure_port('[::]:12345')
server.start()
try:
while True:
time.sleep(_ONE_DAT_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve()
This is the custom_client.py
from __future__ import print_function
import random
import grpc
import custom_pb2
import custom_pb2_grpc
import custom_resources
def custom_get_one_name(stub, idx):
name = stub.GetName(idx)
print("Feater called with id %d returned: %s" %(idx,name))
return
def custom_get_names(stub):
custom_get_one_name(stub,2)
custom_get_one_name(stub,1)
def run():
with grpc.insecure_channel('localhost:12345') as channel:
stub = custom_pb2_grpc.DetailStub(channel)
custom_get_names(stub)
if __name__ == '__main__':
run()
The exact error message I get is:
No handlers could be found for logger "grpc._common"
Traceback (most recent call last):
File "custom_client.py", line 30, in <module>
run()
File "custom_client.py", line 27, in run
custom_get_names(stub)
File "custom_client.py", line 19, in custom_get_names
custom_get_one_name(stub,2)
File "custom_client.py", line 13, in custom_get_one_name
name = stub.GetName(idx)
File "/usr/local/lib/python2.7/dist-packages/grpc/_channel.py", line 513, in __call__
state, call, = self._blocking(request, timeout, metadata, credentials)
File "/usr/local/lib/python2.7/dist-packages/grpc/_channel.py", line 500, in _blocking
raise rendezvous
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
status = StatusCode.INTERNAL
details = "Exception serializing request!"
debug_error_string = "None"
Thanks for the help.
You are trying to pass an integer as the request custom_get_one_name(stub,2) where a Protocol Buffers message of type idx is expected. You should create an idx message and pass that instead like:
custom_get_one_name(stub, custom_pb2_grpc.idx(id=2))

Pyside global menu not works

Why not work global menu in PySide? I'm developing a Qt app in Ubuntu 14.04 LTS and the global menu doesn't work with PySide binding. With PyQt4 it works fine with no problem.
Is it a bug?
With Pyside
from PySide import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(400, 300)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 400, 25))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
self.menuMenu = QtGui.QMenu(self.menuBar)
self.menuMenu.setObjectName(_fromUtf8("menuMenu"))
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(MainWindow)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.actionAsd = QtGui.QAction(MainWindow)
self.actionAsd.setObjectName(_fromUtf8("actionAsd"))
self.actionAsd2 = QtGui.QAction(MainWindow)
self.actionAsd2.setObjectName(_fromUtf8("actionAsd2"))
self.menuMenu.addAction(self.actionAsd)
self.menuMenu.addAction(self.actionAsd2)
self.menuBar.addAction(self.menuMenu.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.menuMenu.setTitle(_translate("MainWindow", "Menu", None))
self.actionAsd.setText(_translate("MainWindow", "Asd", None))
self.actionAsd2.setText(_translate("MainWindow", "Asd2", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
With PyQt4
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(400, 300)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 400, 25))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
self.menuMenu = QtGui.QMenu(self.menuBar)
self.menuMenu.setObjectName(_fromUtf8("menuMenu"))
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(MainWindow)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.actionAsd = QtGui.QAction(MainWindow)
self.actionAsd.setObjectName(_fromUtf8("actionAsd"))
self.actionAsd2 = QtGui.QAction(MainWindow)
self.actionAsd2.setObjectName(_fromUtf8("actionAsd2"))
self.menuMenu.addAction(self.actionAsd)
self.menuMenu.addAction(self.actionAsd2)
self.menuBar.addAction(self.menuMenu.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.menuMenu.setTitle(_translate("MainWindow", "Menu", None))
self.actionAsd.setText(_translate("MainWindow", "Asd", None))
self.actionAsd2.setText(_translate("MainWindow", "Asd2", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Thanks!

swift 2.0 equivalent for NSOpenPanel

i found this swift 1.2 tutorial to open up a panel. but it doesn't work in swift 2.0.
#IBAction func selectFile(sender: AnyObject) {
var openPanel = NSOpenPanel()
openPanel.title = "Select file"
openPanel.beginWithCompletionHandler({(result:Int) in
if (result = NSFILEHandlingPanelOKButton){
print(openPanel.URL!)
}
})
}
I am getting the error unresolved identifier NSOpenPanel, what would be the swift 2.0 equivalent?
I also tried creating Cocoa class under iOS and MacOS without any luck.
If you haven't, try importing AppKit:
import AppKit
You can read the Apple Docs on it.
as a bonus a custom view with popover..
func chooseDestFolder()->URL?{
//it's an OPEN... :)
let dialog = NSOpenPanel()
//dialog.title = "Choose destination folder"
dialog.message = "Choose destination folder"
dialog.showsResizeIndicator = true
dialog.showsHiddenFiles = false
dialog.canChooseDirectories = true
dialog.canChooseFiles = false
dialog.canCreateDirectories = true
dialog.allowsMultipleSelection = false
dialog.allowedFileTypes = [];
let sv = NSView(frame: NSRect(x: 0, y: 0, width: 300, height: 40))
let menu = NSPopUpButton(radioButtonWithTitle: "AAA", target: nil, action: nil)
menu.frame = CGRect(x: 0, y: 10, width: 100, height: 36)
menu.addItems(withTitles: ["JPG", "PDF", ])
sv.addSubview(menu)
dialog.accessoryView = sv
dialog.accessoryView?.wantsLayer = true
//dialog.accessoryView?.layer?.backgroundColor = NSColor.red.cgColor
dialog.isAccessoryViewDisclosed = true
if (dialog.runModal() == NSApplication.ModalResponse.OK) {
let destUrl = dialog.url
return destUrl
} else {
// User clicked on "Cancel"
return nil
}
}

updating score variable from a different class

I'm trying to get my score to carry over to a new scene after the game is over and when this happens the score is coming out at 0. The score is set to 0 in my PlayScene as a default but I need it to read what the score is in ScoreScene when the PlayScene is over. Help Please!!
import SpriteKit
import AVFoundation
class PlayScene: SKScene, SKPhysicsContactDelegate {
let scoreText = SKLabelNode(fontNamed: "System-Bold")
var score = 0
override func didMoveToView(view: SKView) {
self.scoreText.text = "0"
self.scoreText.fontSize = 42
self.scoreText.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame) / 1.075)
func didBeginContact(contact:SKPhysicsContact) {
var scene = ScoreScene(size: self.size)
let skView = self.view as SKView!
skView.ignoresSiblingOrder = true
scene.scaleMode = .ResizeFill
scene.size = skView.bounds.size
skView.presentScene(scene)
func blockRunner() {
for(block, blockStatus) in self.blockStatuses {
var thisBlock = self.childNodeWithName(block)
if blockStatus.shouldRunBlock() {
blockStatus.timeGapForNextRun = random()
blockStatus.currentInterval = 0
blockStatus.isRunning = true
}
if blockStatus.isRunning {
if thisBlock!.position.x > blockMaxX {
thisBlock!.position.x -= CGFloat(self.groundSpeed)
}else {
thisBlock!.position.x = self.origBlockPositionX
blockStatus.isRunning = false
self.score++
if ((self.score % 10) == 0) {
self.groundSpeed++
}
self.scoreText.text = String(self.score)
}
}else {
blockStatus.currentInterval++
}
}
}
and Now when the game is over it switches to Score scene which is below
class ScoreScene: SKScene {
var playScene = PlayScene()
let scoreText = SKLabelNode(fontNamed: "System-Bold")
override func didMoveToView(view: SKView) {
self.scoreText.text = "score: \(playScene.score)"
self.scoreText.fontSize = 42
self.scoreText.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMaxY(self.frame) / 1.075)
You need to create a separate model to hold your data so you can access it from different parts of the app, I normally use a singleton approach so I can create the class only once and access its values anytime I need. What I would do:
create a new class player that keep the details about the player like
score make this class a singleton use this class to populate the
score value through all the scenes of the game
More details about design patterns in swift here (including singleton)
You will find a lot of code demos for singleton in here

Resources