Trying to import module - python

When I am trying to import a method from another class, I am getting the following error.
Traceback (most recent call last):
File "d:\Python\Report-monitoring-system\com\acc\report\main\Main.py", line 7, in <module>
from com.acc.report.report.review.Review import *
ModuleNotFoundError: No module named 'com'
Here's my code below. I want to access methods from Review class which is under com.acc.report.report.review.Review.py and from the class from where I am importing is under com.acc.report.main.Main.py
from com.acc.report.report.review.Review import *
class Main:
program = Tk()
def selectReports(self):
messagebox.showinfo("EDP", "All reports")
def showReports(self):
messagebox.showinfo("EDP", "Select reports")
def Show_Page(self):
# program = Tk()
self.program.title("My Tkinter app")
style = ttk.Style()
style.map("C.TButton",
foreground=[('pressed', 'red'), ('active', 'blue')],
background=[('pressed', '!disabled', 'black'), ('active', 'white')]
)
self.program.geometry("626x431")
reviewObj = Review()
monitor = ttk.Button(name="",text="Monitor",command=reviewObj.reviewReport,style="C.TButton")
monitor.pack(pady=100)
review = ttk.Button(name="",text="Review",command=self.selectReports,style="C.TButton")
review.pack(pady=0)
self.program.mainloop()
# Main method
if __name__ == "__main__":
objectMain = Main()
objectMain.Show_Page()

Related

Object not callable in python class in flask application

This is my first flask application and i tried my best to get it running. Nevertheless i stuck into one error.
I tried to create a python flask app but stuck into an error.
here is my code
flask.py
from test_displayclass import Bartender
class MyFlask:
bartender = Bartender()
def __init__(self):
#self.bartender = Bartender()
self.bartender.test()
from flask import Flask
app = Flask(__name__)
my_flask = MyFlask()
#app.route("/Test")
def Test():
return my_flask.test.APIfunction
if __name__ == "__main__":
app.run(debug=True,port=9999)
test_displayclass.py
import adafruit_ssd1306
import busio
from board import SCL, SDA
from PIL import Image, ImageDraw, ImageFont
class Display():
def __init__(self):
i2c = busio.I2C(SCL, SDA)
self.oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
self.oled.fill(0)
self.oled.show()
def drawImage(self, image):
self.oled(image)
self.oled.show()
class Bartender():
def __init__(self):
self.oled = Display()
def test(self):
image = Image.new("1", (20, 20))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 25)
self.len = len("e")
draw.text(
(0, 40 - 2 // 2),
"e",
font=font,
fill=255,
)
Error is:
Traceback (most recent call last):
File "/home/pi/Smart-Bartender/bartender_flask_new_test.py", line 13, in <module>
my_flask = MyFlask()
File "/home/pi/Smart-Bartender/bartender_flask_new_test.py", line 8, in __init__
self.bartender.test()
File "/home/pi/Smart-Bartender/test_displayclass.py", line 61, in test
self.oled.drawImage(image)
File "/home/pi/Smart-Bartender/test_displayclass.py", line 33, in drawImage
self.oled(image)
TypeError: 'SSD1306_I2C' object is not callable
Can you advice me how to do it the correct waY?
Need of taken the function self.oled.image(image)

Python weird NameError

I have a NameError that I cannot seem to be able to find the reason for. The error trace ends like this.
Traceback (most recent call last):
File ".../new_main.py", line 61, in <module>
if __name__ == "__main__": main()
File ".../new_main.py", line 39, in main
mp = build()
File ".../common.py", line 54, in build
m = r.build_from_config(map_config, character_config)
File ".../config_reader.py", line 148, in build_from_config
item["squares"]
File ".../new_map.py", line 49, in build_map
self.view = MapView(self)
File ".../new_map.py", line 135, in __init__
self.screen = reset_screen()
NameError: name 'reset_screen' is not defined
The class MapView() is in the file new_map.py and that file has this line in the imports:
from common import *
And the file common.py has the following function in it.
def reset_screen():
# check if display has been initialized
if not pygame.display.get_init():
pygame.init()
# set screen
#flags = pygame.FULLSCREEN | pygame.DOUBLEBUF
screen = pygame.display.set_mode( options.window_size )
# fill with black
screen.fill(BLACK)
return screen
What am I missing?
E: here are my imports for each file.
new_main.py:
from common import *
from new_map import Map, MapView
import pygame, sys
common.py:
import pygame
import options
from config_reader import ConfigReader
from constants import *
from coordinates import Coordinates
config_reader.py:
from action import Action
from new_map import Map
from object_type import ObjectType
from squaretype import SquareType
from new_character import Character
from coordinates import Coordinates
import direction
new_map.py:
from square import Square
from common import *
from constants import *
from coordinates import Coordinates
from map_object import MapObject
from object_type import ObjectType
from new_character import Character
from turn import TurnController
import pygame, os
Looking at your trace i can also just figure that in your common.py your are including new_map.py which causes the import in new_map to fail. If i do that to my test files, i get the same error:
my main - which imports both but still won't cause circular reference:
if __name__ == "__main__":
from common import * # <-- this is ok
from new_map import * # <-- this is no problem
do_something()
test()
my commons:
from new_map import * # <--- this will cause the problem
def reset_screen():
return 1
def do_something():
return test()
my new_map:
from common import * # <--- this will fail then
def test():
return reset_screen()
So you will have to split you common.py to the parts using new_map and the other that don't, and in new_map then import the version that holds the functions without new_map inclusion.
common_map.py
from new_map import *
def do_something()
return test()
common_nomap.py
def reset_screen()
return 1
new_map.py:
from common_nomap import *
def test()
return reset_screen()
main.py
if __name__ == "__main__":
from common_map import * # <-- this is ok
from new_map import * # <-- this is no problem
do_something()
test()
2 possible scenarios I can think of:
Circular deps: it looks like common.py activates the function in new_map.py (via config_reader.py), which might cause new_map.py not to import common.py
Is there a common package you might be importing instead of common.py?

Can Python ctypes callback function return a python class instance?

from ctypes import *
class CTest(Structure):
pass
def get_test(id):
c = CTest()
return c
func_type = CFUNCTYPE(CTest, c_int)
test_callback = func_type(get_test)
When I run this script, I got:
Traceback (most recent call last):
File "E:\test\ctypes_test.py", line 11, in <module>
test_callback = func_type(get_test)
TypeError: invalid result type for callback function
What's wrong in the script?
Use ctypes.pyobject :
import ctypes
#from ctypes import *
class CTest(ctypes.Structure):
_fields_ = []
a = 10
def __init__(self):
ctypes.Structure.__init__(self)
def get_test(id):
return CTest()
func_type = ctypes.CFUNCTYPE( ctypes.py_object , ctypes.c_int )
test_callback = func_type( get_test )
print test_callback(1).a
>> 10

Cocos2d: AttributeError: 'Director' object has no attribute '_window_virtual_width'

We are using the cocos2d framework to create a game. We're completely new to this framework, so we cannot get the director object to work as we are expecting. Here is our code skeleton:
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter():
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def main():
scene = TestScene()
director.init(world_width, world_height, do_not_scale=True)
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
So for some reason the director doesn't have all the attributes we want.
Our stack trace is:
Traceback (most recent call last):
File "map.py", line 49, in <module>
main()
File "map.py", line 39, in main
scene = TestScene()
File "map.py", line 29, in __init__
super(TestScene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/scene.py", line 95, in __init__
super(Scene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/cocosnode.py", line 114, in __init__
self.camera = Camera()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 56, in __init__
self.restore()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 76, in restore
width, height = director.get_window_size()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/director.py", line 522, in get_window_size
return ( self._window_virtual_width, self._window_virtual_height)
AttributeError: 'Director' object has no attribute '_window_virtual_width'
You need to initialise the director before you instantiate your first scene. The director is the global object that initialises your screen, sets up the Cocos2D framework, etc.
I found a few other errors:
You need to change ColorLayer to be fully qualified, e.g. cocos.layer.ColorLayer.
on_enter needs to have self as the first argument.
You need to define f_refresh_marks in your TestScene class.
Here's a working copy of the code. (Working, in the sense that it does not throw errors, not that it does any sort of scrolling.)
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = cocos.layer.ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter(self):
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def f_refresh_marks(self):
pass
def main():
director.init(world_width, world_height, do_not_scale=True)
scene = TestScene()
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
if __name__ == '__main__': main()
I had the same issue (with a very similar stack trace) and it was because I was trying to create a layer before calling director.init(). Moving director.init() to earlier in the code fixed it for me.

Insert Text into a TextBuffer via a Function - python

I have following problem:
How can i insert text in my textbuffer?
Interface.py
class MainWindow:
def __init__(self):
# Build our Interface from the XML/Glade file
gladefile = "MainWindow.glade"
try:
self.builder = Gtk.Builder()
self.builder.add_from_file(gladefile)
except:
print("Failed to load Glade file: %s" % gladefile)
# Connect signals
self.builder.connect_signals(self)
# Get the widgets
self.window = self.builder.get_object("MainWindow")
...
# TextViews
self.TextViewCommandInput = self.builder.get_object("TextViewCommandInput")
self.TextViewCommandOutput = self.builder.get_object("TextViewCommandOutput")
...
def DrawCommandView(output):
TextBufferCommandInput = MainWindow.TextViewCommandInput.get_buffer()
TextBufferCommandInput.insert_at_cursor(output + "\n")
And import "DrawCommandView" in a file
Commands.py
from Interface import MainWindow, DrawCommandView
output = "Hello World"
DrawCommandView(output)
if __name__ == "__main__":
StartMainWindow = MainWindow()
StartMainWindow.main()
But I keep getting this error:
Traceback (most recent call last):
File "/home/user/Dokumente/Workspace/project/Commands.py", line 5, in <module>
DrawACommandView(output)
File "/home/user/Dokumente/Workspace/project/Interface.py", line 182, in DrawCommandView
TextBufferCommandInput = MainWindow.TextViewCommandInput.get_buffer()
AttributeError: class MainWindow has no attribute 'self'
Thanks for your help!
greetz
When you say TextBufferCommandInput = MainWindow.TextViewCommandInput.get_buffer()
You are asking for a class attribute in MainWindow named TextViewCommandInput. You don't have a class attribute TextViewCommandInput, you have an instance attribute TextViewCommandInput. You need to pass an instance of MainWindow into DrawCommandView in order to get to TextViewCommandInput.
I believe you have to set_text() instead of get_buffer().
See the set_text() documentation.
Then later get_buffer() can retrieve the text inserted by set_text().
Here are some methods I've been using to have a generic way to use the buffer.
def GetTextBuffer(self):
self.text_buffer = self.text_edit.get_buffer()
# self.text_edit is a Gtk.TextView() instance
# to get the text buffer from TextView
# buffer.get_text( start iterator, end iterator, bool )
# the third argument set to True = Include hidden characters
# third argument set to False = Don't include hidden characters
# hidden characters would be visual formatting markup and such
return self.text_buffer.get_text(
self.text_buffer.get_start_iter(),
self.text_buffer.get_end_iter(),
False)
def SetTextBuffer(self, to_buffer):
# to_buffer is user input from widgets, or default values set at run time.
text_buffer = self.text_edit.get_buffer()
text_buffer.set_text(to_buffer)

Categories