PyQt. Get errors trying to separate GUI from logic - python

So I try to separate GUI part from logic part, but I can't call logic function from GUI part. Here's the simplified version of the code:
GUI part
import logic
class Program(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.first_list = QListWidget(self)
self.first_list.setGeometry(15, 35, 140, 42)
add_to_list_button = QPushButton('Add', self)
add_to_list_button.setGeometry(165, 35, 30, 20)
add_to_list_button.clicked.connect(lambda: logic.addToList())
self.second_list = QListWidget(self)
self.second_list.setGeometry(205, 35, 140, 192)
for i in range(30):
self.second_list.addItem(logic.list_one[i][3])
And the logic part
import gui
# list_one and list_two go here
def addToList(self):
for i in range(len(gui.Program.second_list)):
if list_one[i][3] == str(gui.Program.second_list.currentItem().text()):
index = i
list_two.append(list_one[index])
When I run the code and press the Add button I get:
Traceback (most recent call last):
File "/************/gui.py", line 30, in <lambda>
add_to_list_button.clicked.connect(lambda: logic.addToList())
TypeError: addToList() missing 1 required positional argument: 'self'
And when I add self and press the button I get:
add_to_list_button.clicked.connect(lambda: logic.addToList(self))
Traceback (most recent call last):
File "**************/gui.py", line 30, in <lambda>
add_to_list_button.clicked.connect(lambda: logic.addToList(self))
File "**************/logic.py", line 23, in addToList
for i in range(len(gui.Program.second_list)):
AttributeError: type object 'Program' has no attribute 'second_list'
Plus I get lots of other errors like "Cannot find reference 'connect' in 'function', etc.". When the whole code is in one file it works fine. But I have no idea how to separate it right. Sorry for lots of code examples.

Related

Function is not accessed

this is my code:
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")
on hovering on on_enter_pressed function, it's showing function is not accessed and I'm getting the following error:
Traceback (most recent call last):
File "GUI.py", line 91, in <module>
app = ChatApplication()
File "GUI.py", line 15, in __init__
self._setup_main_window()
File "GUI.py", line 76, in _setup_main_window
self.msg_entry.bind("<Return>", self._on_enter_pressed)
AttributeError: 'ChatApplication' object has no attribute '_on_enter_pressed'
(I'm using tkinter in python to implement GUI.)
How can I solve this?
You have wrong indentations - _on_enter_pressed has to be outside __init__
def __init__(self):
# ... code ..
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
# outside `__init__`
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")

bbox works when inputting exact coordinates within module but fails with variable containing identical data

I'm having an issue trying to make a screen grab of an area defined by lines in a config file:
The following code:
def coordstore(): # check line 1 of config file (screencap name)
f=open('config.txt')
line=f.readlines()
coordstore.x1,coordstore.y1,coordstore.x2,coordstore.y2 = (line[4]).strip(),(line[5]).strip(),(line[6]).strip(),(line[7]).strip() # note: confusing. 0=line 1, 1=line2 etc.
coordstore.coords = coordstore.x1+',',coordstore.y1+',',coordstore.x2+',',coordstore.y2
coordstore.stripped = ' '.join((coordstore.coords))
print(coordstore.stripped)
return(coordstore.stripped)
coordstore()
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=(coordstore.stripped)) # X1,Y1,X2,Y2
im.save('tc.png')
screenshot()
prints exactly this value: 10, 20, 100, 300
it then fails with this Traceback:
Traceback (most recent call last):
File "file location", line 82, in <module>
screenshot()
File "file location", line 80, in screenshot
im = ImageGrab2.grab(bbox=(coordstore.stripped)) # X1,Y1,X2,Y2
File "PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 67, in grab
to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)
File "PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 38, in _grab
x1, y1, x2, y2 = bbox
ValueError: too many values to unpack (expected 4)
If I manually replace (bbox=(coordstore.stripped)) with (bbox=(10, 20, 100, 300)) which is literally identical to what the variable prints, the code works perfectly but is not useful for my needs. What am I not seeing? Thanks for the help!
UPDATE:
I have tried another approach.
def coordstore(): # check line 1 of config file (screencap name)
f=open('config.txt')
line=f.readlines()
coordstore.x1 = (line[4]).strip()
coordstore.y1 = (line[5]).strip()
coordstore.x2 = (line[6]).strip()
coordstore.y2 = (line[7]).strip()
print(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2)
return(coordstore.x1, coordstore.y1, coordstore.x2, coordstore.y2)
coordstore()
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2+',')) # X1,Y1,X2,Y2
im.save('tc.png')
screenshot()
This prints
10, 20, 100, 300
but returns the following Traceback errors:
Traceback (most recent call last):
File "module location", line 84, in <module>
screenshot()
File "module location", line 82, in screenshot
im = ImageGrab2.grab(bbox=(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2+',')) # X1,Y1,X2,Y2
File "\PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 67, in grab
to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)
File "\PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 42, in _grab
raise ValueError('bbox y2<=y1')
ValueError: bbox y2<=y1
As you have mentioned in comments the value of coordstore.stripped is string. And expected argument by ImageGrab2.grab is type of tuple so, first you have to convert it into tuple.
Update the method like this:
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=tuple(map(int, coordstore.stripped.split(', ')))) # X1,Y1,X2,Y2
im.save('tc.png')

AttributeError when trying to change tkinter label color with bound command

I am trying to create a tkinter label that changes color when clicked to show that it has been visited. I keep getting an attribute error saying that Show_Label has no attribute 'fg'. Please help! Here is the code being used.
class Sheet_Label(Label):
def __init__(self,master,text):
Label.__init__(self,master,text=text,cursor="hand2",font="Times 16 underline",fg="blue")
def button_click(event):
if self.fg =="blue":
self.fg = "purple"
else:
self.fg = "purple"
location = os.getcwd()
file = webbrowser.open_new(location + '\\' + "hello.txt")
self.bind("<Button-1>",func=button_click)
def sheets_view():
sheets_window = Toplevel(window)
hello = modules.Sheet_Label(master=sheets_window,text="Hello")
hello.pack(padx=10,pady=10)
sheets_window.title("Production Sheets")
sheets_window.focus()
x = (screen_width/2) - (500/2)
y = (screen_height/2) - (500/2)
sheets_window.geometry("%dx%d+%d+%d" % (500,500,x,y))
sheets_window.resizable(0,0)
Here is the error message:
Traceback (most recent call last):
File "C:\Users\napaf\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "inventory.py", line 311, in sheets_view
hello = modules.Sheet_Label(master=sheets_window,text="Hello")
File "C:\Users\napaf\Documents\Programming\adco_project\modules.py", line 24, in __init__
self.action = action
NameError: name 'action' is not defined
PS C:\Users\napaf\Documents\Programming\adco_project> python inventory.pyException in Tkinter callback
Traceback (most recent call last):
File "C:\Users\napaf\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\napaf\Documents\Programming\adco_project\modules.py", line 27, in button_click
if self.fg =="blue":
AttributeError: 'Sheet_Label' object has no attribute 'fg'
You aren't initializing self.fg until button_click has been called, but at that point it's too late because you're trying to reference self.fg before setting it.
Also, self.fg is not the same as the fg attribute when you create the widget (eg: Label(..., fg="blue"). If you want to get the value of the widget attribute you should use self.cget('fg') or use the shortcut self['fg']. If you want to set it from within the class itself you should use self.configure(fg="purple").

Error for python code

The following code return an error KeyError: 500
def my_func(self, limit, list_type, **args):
type2abbr = {"allcategories": "ac", "categorymembers":"cm"}
abbr = type2abbr[list_type]
yield abbr
if __name__ == "__main__":
abbr = my_func(500, "categorymembers")
print abbr
Output:
Traceback (most recent call last):
File "dater.py", line 72, in
bot.start()
File "dater.py", line 56, in start
for title, text in self.pages:
File "dater.py", line 25, in page_generator
for item in self.cats:
File "/home/ceradon/api.py", line 305, in list
abbr = type2abbr[list_type]
KeyError: 500
Can anyone help me figure this out please?
You've implemented my_func as if it were a method (i.e. assuming self) but you are not calling it on any object.
Either you should have an object, e.g. x.my_func(...), or you should remove self, from the argument list.

adding items to treeview in PyGObject

I have a GUI created in Glade, and I would like to populate the treeview widget. Here is the relevant part of my code
def __init__(self):
.....
self.fill_store()
self.add_column(self.widget('treeview_preview'))
self.widget('treeview_preview').set_pixbuf_column(0)
def fill_store(self):
self.widget('liststore_preview').clear()
foo = GdkPixbuf.Pixbuf.new_from_file('9.png')
da = Gtk.Image.new_from_pixbuf(foo)
self.widget('liststore_preview').append([da])
def add_column(self, treeview):
renderer = Gtk.CellRendererPixbuf()
column = Gtk.TreeViewColumn("Preview", renderer, pixbuf = 0)
column.set_sort_column_id(0)
treeview.append_column(column)
Yet, when I try to run the code, I get an error, which informs me that renderer is not defined. The offending line is
column = Gtk.TreeViewColumn("Preview", renderer, pixbuf = 0)
Can someone point out the error? In case it helps, here is the traceback
Traceback (most recent call last):
File "test.py", line 10, in <module>
class test:
File "test.py", line 48, in test
column = Gtk.TreeViewColumn("Preview", r, pixbuf = 0)
NameError: name 'r' is not defined
Thanks,
v923z
Are you sure you don't have an typo like this?
>>> something = 1
>>> somthing # typo, left out 'e'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'somthing' is not defined

Categories

Resources