How to display image in wxpython? - python-3.x

Please help me with this code. I want to display image in the frame :
import wx
import os
class frame(wx.Frame):
'''frame class that display an image'''
def __init__(self, image, parent=None, id=-1,
pos=wx.DefaultPosition, title='Hello, wxPyhton!'):
'''creat a frame instance and display image.'''
temp = image.ConvertToBitmap()
size = temp.GetWidth(), temp.GetHeight()
wx.Frame(parent, id, pos, title, size)
self.bmp = wx.StaticBitmap(parent=self, bitmap=temp)
class App(wx.App):
'''Application class.'''
def OnInit(self):
image = wx.Image('clem.jpg', wx.BITMAP_TYPE_JPEG)
self.frame = frame(image)
self.frame.Show()
return True
if __name__ == '__main__':
app = App()
app.MainLoop()
But i got this error:
Traceback (most recent call last):
File "C:/PycharmProjects/WXPYHTON/hello.py", line 18, in OnInit
self.frame = frame(image)
File "C:/PycharmProjects/WXPYHTON/hello.py", line 11, in __init__
wx.Frame(parent, id, pos, title, size)
TypeError: Frame(): arguments did not match any overloaded call:
overload 1: too many arguments
overload 2: argument 3 has unexpected type 'Point'
OnInit returned false, exiting...
Process finished with exit code 1
please help this code. i don't know where i'm getting it wrong.
I've changed it but i'm still getting this error
Traceback (most recent call last):
File "C:/PycharmProjects/WXPYHTON/hello.py", line 18, in OnInit
self.frame = frame(image)
File "C:/PycharmProjects/WXPYHTON/hello.py", line 12, in __init__
self.bmp = wx.StaticBitmap(parent=None, bitmap=temp)
TypeError: StaticBitmap(): arguments did not match any overloaded call:
overload 1: 'parent' is not a valid keyword argument
overload 2: 'bitmap' is not a valid keyword argument
OnInit returned false, exiting...
please check my self.bmp, if it is correct. Thanks

You are not initialising the frame properly and you are using keywords as variable names.
Change:
wx.Frame(parent, id, pos, title, size)
To:
wx.Frame.__init__(self,parent,id,pos=pos,title=title,size=size)
and it should work.

Related

Pygtk Liststore most recent call last after Liststore update

I created simple code in PyGtk that displays a list of names. After clicking the Update button, the list of names will be updated. Unfortunately, I can't get rid of the "most recent call last" error that appears after clicking the Update button. Can anyone advise me on the problem? This is probably a problem with a line of code under "# select and row".
EDIT:
Script returns error message:
Traceback (most recent call last):
File "/home/radek/Desktop/stackowr1.py", line 18, in choiceRow
line = model[treeiter][0]
File "/usr/lib/python3/dist-packages/gi/overrides/Gtk.py", line 849, in __getitem__
aiter = self._getiter(key)
File "/usr/lib/python3/dist-packages/gi/overrides/Gtk.py", line 837, in _getiter
aiter = self.get_iter(key)
File "/usr/lib/python3/dist-packages/gi/overrides/Gtk.py", line 871, in get_iter
path = self._coerce_path(path)
File "/usr/lib/python3/dist-packages/gi/overrides/Gtk.py", line 846, in _coerce_path
return TreePath(path)
File "/usr/lib/python3/dist-packages/gi/overrides/Gtk.py", line 1210, in __new__
path = ":".join(str(val) for val in path)
TypeError: 'NoneType' object is not iterable
My code:
```python
# -*- coding: utf-8 -*-
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
class MyWindow(Gtk.Window):
def __init__(self):
super(MyWindow, self).__init__()
self.set_border_width(3)
self.set_default_size(800, 600)
self.name1 = "John"
self.name2 = "George"
def choiceRow(selection):
model, treeiter = selection.get_selected()
line = model[treeiter][0]
print(line)
def update_name(self):
self.name1 = "Jeane"
self.name2 = "Margot"
print(self.name1, self.name2)
win.liststore.clear()
win.liststore.append([self.name1])
win.liststore.append([self.name2])
button = Gtk.Button(label = "Update")
button.connect("clicked", update_name)
self.layout = Gtk.Layout()
self.tree = Gtk.TreeView()
self.liststore = Gtk.ListStore(str)
self.tree.set_model(self.liststore)
self.liststore.append([self.name1])
self.liststore.append([self.name2])
render = Gtk.CellRendererText()
self.column = Gtk.TreeViewColumn("ID", render, text=0)
self.tree.append_column(self.column)
# select a row
selectetRow = self.tree.get_selection()
selectetRow.connect("changed", choiceRow)
self.layout.put(self.tree, 0,0)
self.layout.put(button, 0,100)
self.add(self.layout)
win = MyWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
Gtk.TreeSelection.get_selected returns None when nothing is selected, after the update call there's nothing selected so you get None for treeiter and you try to access model[None][0] which obviously must fail. You need to check whether the returned iter is valid before trying to use it so just change your choiceRow function to
def choiceRow(selection):
model, treeiter = selection.get_selected()
if treeiter:
line = model[treeiter][0]
print(line)

TypeError: __init__() got an unexpected keyword argument '__no_builder' Kivy

I'm trying to add a def __init__(self) to my code and when I run the kivy program I get this:
Traceback (most recent call last):
File "/Users/acrobat/Desktop/dive/test.py", line 78, in <module>
''')
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/kivy/lang.py", line 1921, in load_string
self._apply_rule(widget, parser.root, parser.root)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/kivy/lang.py", line 2085, in _apply_rule
self._apply_rule(child, crule, rootrule)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/kivy/lang.py", line 2082, in _apply_rule
child = cls(__no_builder=False)
TypeError: __init__() got an unexpected keyword argument '__no_builder'
Here is the code:
The def __init__(self) is in a PlayerImage Class which is a widget that I'm trying to move across the screen
class PlayerImage(Image):
angle = NumericProperty(0)
def __init__(self):
super().__init__()
def on_touch_down(self, touch):
# self.currentstate = self.states["person.zip/"]
Animation.cancel_all(self)
angle = degrees(atan2(touch.y - self.center_y,
touch.x - self.center_x))
Animation(center=touch.pos, angle=angle).start(self)
# self.currentstate = self.states["personred/rest.png/"]
I'm not using a kv lang file so here is my build code:
root = Builder.load_string('''
Widget:
Widget:
PlayerImage:
source: './rpgArt/person.zip'
allow_stretch: True
keep_ratio: True
PlayerImage2:
source: './rpgArt/personred.zip'
allow_stretch: True
keep_ratio: True
''')
EDIT: added kivy tag
Replace:
def __init__(self):
super().__init__()
With:
def __init__(self, **kwargs):
super(PlayerImage, self).__init__(**kwargs)
You are creating a subclass of an object without passing the keyword arguments which Kivy requires.
I also don't think the __init__() is required by Kivy, I think it might look it up automatically for you from the parent, but that I'm not sure with.
Edited: Like Kevin said in the comments since you are using Python 3 you can use the zero arguments of super() which would be just as valid.

AttributeError when monkey patching an object in python

I tried to monkey patch an object in Python.
class C:
def __init__(self):
self.__n = 0
def f(self):
self.__n += 1
def __str__(self):
return str(self.__n)
c = C()
def up(self):
self.__n += 2
import types
c.up = types.MethodType(up, c)
c.up()
But I got an AttributeError
Traceback (most recent call last):
File "untitled4.py", line 19, in <module>
c.up()
File "untitled4.py", line 15, in up
self.__n += 2
AttributeError: 'C' object has no attribute '__n'
How can I fix the error?
As your up function isn't declared inside a class, it is not possible to apply name mangling rules to its locals, while it is applied for the attribute name. Therefore you'd need to apply the name mangling manually in your function:
def up(self):
self._C__n += 2

AttributeError: 'MainWindow' object has no attribute 'dev'

Hy,
Yeah so, i am writing an python3 programm, that should send the content of an file to an LPC1758.
For testing i will write a simple string above USB. I use libusb1.0 ....
But every time i become the same error, even if i rename "dev" into "device" the error is the same.
--> AttributeError: 'MainWindow' object has no attribute 'dev'<--
class MainWindow(QtGui.QMainWindow, form_class):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.pb_send.clicked.connect(self.pb_send_clicked)
self.pb_open.clicked.connect(self.pb_open_clicked)
self.pb_exit.clicked.connect(self.pb_exit_clicked)
# SEND button event handler
def pb_send_clicked(self):
send = "Yo Man"
bulk_out_ep = 0x05
bulk_in_ep = 0x82
interface = 0
length = 30
dev = usb.core.find(idVendor= 0xfefe, idProduct= 0x0001)
cfg = usb.control.get_configuration(dev) # get current configuration
print(dev)
if dev is None:
self.USB_label.setText("Device not found !!!")
raise ValueError('Device not found')
else:
self.USB_label.setText("Device found")
found = 1
if(cfg != 1): # check if device is configured
usb.DeviceHandle.setConfiguration(self, 1)
usb.util.claim_interface(dev, interface)
usb.DeviceHandle.bulkWrite(self,bulk_out_ep,send)
print("wrote to estick")
readData = usb.DeviceHandle.bulkRead(self, bulk_in_ep, length)
print("read from estick: "+ readData)
usb.util.release_interface(dev, interface)
This is what Stacktrace shows:
Traceback (most recent call last):
File "/home/user/workspace_Qt/ESS_project/ess_project.py", line 93, in pb_send_clicked
readData = usb.DeviceHandle.bulkRead(self,endpoint=bulk_in_ep,size=length)
File "/usr/lib/python3.3/usb/legacy.py", line 159, in bulkRead
return self.dev.read(endpoint, size, self.__claimed_interface, timeout)
AttributeError: 'MainWindow' object has no attribute 'dev'
dev is a member of the class DeviceHandle which is the type of the first parameter expected by the setConfiguration functions.
And setConfiguration expects 2 parameters instead of 1, because you are calling the method on the class usb.DeviceHandle instead of calling it on an object of type usb.DeviceHandle, you should use:
dev.setConfiguration(1)
(same thing for bulkWrite and bulkRead).
Also the get_configuration method returns a Configuration object instead of a number, so cfg != 1 will always be true (this may work with cfg.index != 1 instead but I'm not sure).

Module Import from tkinter Widget

Not long ago I asked an question on how to import from an input statement. Nailed it. Now I'm upgrading my lengthy code to a GUI for the user. Same problem. How do I import a module based on user input from the tkinter widget Entry.
I originally had:
var1=__import__(input("Enter a module: "))
And attempted something like this:
import tkinter
var1=__import__(tkinter.Entry(top, bd=5)).pack()
A few different phrasings all resulted in the basic error:
TypeError: __import__() argument 1 must be str, not Entry
I have a few different methods still on my list to try. For example:
var1=Entry(top, bd=5).grid(row=7)
var2=Entry.get(var1)
var=__import__(var2)
This gives me the rather awful error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "C:\Python33\Doc\Project\testing.py", line 21, in finish
var2=Entry.get(var1)
File "C:\Python33\lib\tkinter\__init__.py", line 2512, in get
return self.tk.call(self._w, 'get')
AttributeError: 'NoneType' object has no attribute 'tk'
You need Entry instance to work with it.
This way:
my_entry = Entry(top, bd=5) # you get object (Entry instance)
my_entry.grid(row=7) # you call object method grid()
entry_text = my_entry.get() # you call object method get()
var = __import__(entry_text)
BTW:
This way you get result of grid() function, not Entry instance.
var1 = Entry(top, bd=5).grid(row=7) # grid() returns always None
see
my_entry = Entry(top, bd=5)
grid_result = my_entry.grid(row=7) # grid() returns always None
var1 = grid_result
In this code you try to pack() imported library :)
var1 = __import__(tkinter.Entry(top, bd=5)).pack()
see
my_entry = Entry(top, bd=5) # you get object
imported_library = __import__(my_entry) # object can't be argument for __import__
var1 = imported_library.pack() # you can't pack library

Resources