I am new in python. I want to update an image on label1. But function 'def browse' always give me blank label instead. Seems the code does not get the image or it failed to update the label, and the program did not give any error message. Did i missed something here? Also, print command below setPixmap command is executed. i am using python 2.7 and PyQT4.
Thanks in advance
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import os, sys
import cv2
from PIL.ImageQt import ImageQt
class GuiCakep(QtGui.QWidget):
global label1, label2
def __init__(self):
super(GuiCakep, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 1000, 600)
self.setWindowTitle('Single Browse')
self.label1 = QtGui.QLabel(self)
self.label1.setFrameShape(QtGui.QFrame.Box)
self.label1.setGeometry(QtCore.QRect(20, 10, 451, 451))
pixmap = QPixmap('1stimage.jpg')
self.label1.setPixmap(pixmap)
self.label2 =QtGui.QLabel(self)
self.label2.setFrameShape(QtGui.QFrame.Box)
self.label2.setGeometry(QtCore.QRect(481, 10, 451, 451))
btn = QtGui.QPushButton('Browse', self)
btn.resize(btn.sizeHint())
btn.clicked.connect(self.browse)
btn.move(775, 500)
self.show()
def browse(self):
filePath = QtGui.QFileDialog.getOpenFileName(self, 'a file','*.jpg')
fileHandle = open(filePath, 'r')
pixmap = QPixmap('filePath')
self.label1.setPixmap(pixmap)
print("Whoa awesome")
def main():
app = QtGui.QApplication(sys.argv)
w = GuiCakep()
app.exec_()
if __name__ == '__main__':
main()
You are creating a Pixmap with 'filePath' as argument. This is a string, not your variable filePath.
Remove the both ' and this should update the label.
Related
When I try to graph something with matplotlib in a tkinter window, it simply won't show up. If I remove the tkinter specific part, and just do a basic plt.plot(...) and plt.show() it shows up in my regular text output field. However, in this case I would like it to show up in a tkinter window. I Believe its because I am running this on a mac (macOS 10.12.4), however I cannot figure out how to get it to show up in the tkinter window.
import numpy as np
import Tkinter as tk
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
root = tk.Tk()
fig = plt.figure(1)
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
plt.plot(t,s)
canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()
def update():
s = np.cos(np.pi*t)
plt.plot(t,s)
plt.show()
plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()
As I said, I believe its due to the fact that I am running on MacOS. Also FYI when I run this a blank tkinter window shows up with the update button, but no graph. The Graph DOES however show up in the regular text output but I want it in the tkinter window for a GUI. Please Help!
You need to update the figure that is already in the tk canvas, instead of showing a new one with plt.show(). In this case there is only one figure open, so plt.plot() will actually work (although it might fail in more complex scenarios). What remains is to redraw the canvas, fig.canvas.draw_idle() after plotting.
import numpy as np
import Tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
root = tk.Tk()
fig = plt.figure(1)
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
plt.plot(t,s)
canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()
def update():
s = np.cos(np.pi*t)
plt.plot(t,s)
fig.canvas.draw_idle()
plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()
For the future and to be on the save side, try to avoid using pyplot when embedding matplotlib into GUIs. This prevents you from having issues like the one reported here.
import numpy as np
import Tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
root = tk.Tk()
fig = Figure()
ax = fig.add_subplot(111)
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
ax.plot(t,s)
canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()
def update():
s = np.cos(np.pi*t)
ax.plot(t,s)
fig.canvas.draw_idle()
plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()
I am trying to make a simple maths quiz game that shows Numbers and when I press space it shows the result , the Application launch with a QTdyalog GUI first and after I finish configuring the gameplay a Kivy screen should show up and the game starts until the user press escape it gets back to the config GUI
here is the Programm skeleton
import kivy
from kivy.app import App
from kivy.uix.label import Label
import sys
from PyQt4 import QtCore, QtGui, uic
qtCreatorFile = "ConfigForm.ui" # Enter file here.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class Playy(App): #the Kivy app
def build(self):
l = Label(text='Hello world')
return l
class Conf(QtGui.QDialog, Ui_MainWindow): #the COnfiguration Gui
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.buttonBox.accepted.connect(self.oky)
self.buttonBox.rejected.connect(self.notok)
def oky(self):
print "OK OK OK OK" #creating a Kivy app instance and running it
ins = Playy()
ins.run()
def notok(self):
print "cancel cancel"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = Conf()
window.show()
sys.exit(app.exec_())
I am only having Issue with making functions inside the Kivy app class and passing arguments Into them and also handling Objects properties such as label text this is my first Kivy experiment tell me what do you think
I have a BoxLayout defined in a kivy file, and I am trying to add a label to this BoxLayout from a python file. Below are my python and kivy scripts. When I try to run the program as is, it fails, and I get an error message stating:
"properties.pyx", line 654, in kivy.properties.ObservableDict.__getattr__ (kivy\properties.c:9590)
KeyError: 'box'
How can I add a label (defined in dummy.py) to the BoxLayout (defined in dummy.kv) from dummy.py?
dummy.py shown below:
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder
Builder.load_file('dummy.kv')
class test(BoxLayout):
box = ObjectProperty()
def __init__(self):
label = Label(text='Hello')
self.ids.box.add_widget(label)
class Test(App):
def build(self):
return test()
if __name__ == '__main__':
Test().run()
dummy.kv shown below:
#:kivy 1.8
<test>:
box: box
BoxLayout:
orientation: 'vertical'
id: box
You didn't initialize your test class properly:
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder
Builder.load_file('dummy.kv')
class test(BoxLayout):
box = ObjectProperty()
def __init__(self):
label = Label(text='Hello')
super(test,self).__init__() #-------ADD THIS LINE
print(self.ids)
self.ids.box.add_widget(label)
class Test(App):
def build(self):
return test()
if __name__ == '__main__':
Test().run()
If those are really your filenames, the kv file is never loaded, so the BoxLayout with id 'box' does not exist. Rename the kv file to test.kv or use kivy.lang.Builder.load_file('dummy.kv').
I am trying to write a program that has a pyplot (as in matplotlib.pyplot) within a Tkinter GUI which can be updated. Basically what I want is a program with a Tkinter interface to be displaying some data on a pyplot, then when the program gets some new data I want to update the pyplot to contain the new data.
Here is a minimal example:
import numpy as np
import Tkinter as tk
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
root = tk.Tk()
fig = plt.figure(1)
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
plt.plot(t,s)
canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()
def update():
s = np.cos(np.pi*t)
plt.plot(t,s)
plt.draw()
plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()
What I expect to happen is, for a window to pop up with a plot containing a sine wave and a button. When I press the button a cosine wave should appear on the plot.
What actually happens when I run the program is that a window pops up with a plot containing a sine wave and a button. However when I press the button nothing happens. The plot does not seem to be updating.
I'm probably making some newbie mistake but I can't find any examples online of doing this sort of thing. What is going wrong here and how would I get what I want?
Any help would be greatly appreciated!
I figured it out, I need to call the draw() method on the figure's canvas attribute in order to get it to redraw, the corrected code is below. Also anyone who is encountering this or similar problems should probably look at matplotlib.animate if they need to be dynamically updating their pyplot
import numpy as np
import Tkinter as tk
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
root = tk.Tk()
fig = plt.figure(1)
plt.ion()
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
plt.plot(t,s)
canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()
def update():
s = np.cos(np.pi*t)
plt.plot(t,s)
#d[0].set_ydata(s)
fig.canvas.draw()
plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()
Is there any way to make the message/title in the label fits into the popup ?
'message' or 'title' can be a long text that goes beyond the borders of the popup .
def popup_display(self, title, message):
btnclose = Button(text='Close me', size_hint_y=None, height=50)
content = BoxLayout(orientation='vertical')
content.add_widget(Label(text=message))
content.add_widget(btnclose)
popup = Popup(content=content, title=title,
size_hint=(None, None),
size=(300, 300),
auto_dismiss=False)
btnclose.bind(on_release=popup.dismiss)
popup.open()
Label has a text_size property, which allows to constraint its size to given bounding box. You can bind it to available size:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.app import App
from kivy.lang import Builder
from functools import partial
class TestApp(App):
def build(self):
return Button(on_press=partial(self.popup_display, "title", "bar "*80))
def popup_display(self, title, message, widget):
btnclose = Button(text='Close me', size_hint_y=None, height=50)
l = Label(text=message)
l.bind(size=lambda s, w: s.setter('text_size')(s, w))
content = BoxLayout(orientation='vertical')
content.add_widget(l)
content.add_widget(btnclose)
popup = Popup(content=content, title=title, size_hint=(None, None), size=(300, 300), auto_dismiss=False)
btnclose.bind(on_release=popup.dismiss)
popup.open()
if __name__ == '__main__':
TestApp().run()
Text that won't fit will get removed. If you want to have it all you should use ScrollView inside of your popup.
As for title, it's not a Label but a string, so the best you can do is to add newlines:
return Button(on_press=partial(self.popup_display, "multiline\ntitle", "bar "*80))
Here'a a simpler version without BoxLayout and Button:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from functools import partial
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
class TestApp(App):
def build(self):
return Button(on_press=partial(self.popup_display, "title", "bar "*80))
def popup_display(self, title, message, widget):
l = Label(text=message)
l.bind(size=lambda s, w: s.setter('text_size')(s, w))
popup = Popup(content=l, title=title, size_hint=(None, None), size=(300, 200), auto_dismiss=True)
popup.open()
if __name__ == '__main__':
TestApp().run()
Simply click outside the popup to close it.