adding items to treeview in PyGObject - python

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

Related

KeyError with custom derived quantity

I have defined a new derived dimension with
[molar_energy] = [energy] / [substance]
However, if I do the following it complains:
>>> UR.get_compatible_units('[molar_energy]')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 881, in get_compatible_units
equiv = self._get_compatible_units(input_units, group_or_system)
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 2082, in _get_compatible_units
ret = super()._get_compatible_units(input_units, group_or_system)
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 1835, in _get_compatible_units
ret = super()._get_compatible_units(input_units, group_or_system)
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 891, in _get_compatible_units
return self._cache.dimensional_equivalents[src_dim]
KeyError: <UnitsContainer({'[length]': 2, '[mass]': 1, '[substance]': -1, '[time]': -2})
I saw that there is a conversion included in a context but I don't use it. What I am doing wrong?
Thanks for your help
PS: logged issue https://github.com/hgrecco/pint/issues/1418
Just leaving the solution here for anyone who faces this issue as well.
I just added a made-up unit and it worked
# Molar Energy
[molar_energy] = [energy] / [substance]
mol_en = J / mol

Change builtin function - Print

I'm trying to change the print builtin function from python.
The reason I'm trying to achieve this is cause my application has an verbose sys.argv, and I want to use print to console out the message whether the verbose is True or False.
I've tried to use create a new function, but I get a recursion error:
>>> import builtins
>>> def new_print(*args, **kwargs):
... print('print:', *args, **kwargs)
...
>>> old_print = builtins.print
>>> old_print(1)
1
>>> builtins.print = new_print
>>> print(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in new_print
File "<stdin>", line 2, in new_print
File "<stdin>", line 2, in new_print
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
I've tried using sys.stdout():
>>> import builtins
>>> import sys
>>> def new_print(*args, **kwargs):
... sys.stdout(*args, **kwargs)
...
>>> old_print = builtins.print
>>> old_print(1)
1
>>> builtins.print = new_print
>>> print(1
... )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in new_print
TypeError: '_io.TextIOWrapper' object is not callable
Although using those options, none seemed to work properly.
I need the new print function to be accesible for all my module files, without needing to import it every time. That's why I'm trying to change the builtin function, but I'm not sure that changing this in my init.py file will make a difference for my other files.
Please, if you have any idea on what could help me, please leave it below.
You almost had it. Call old_print in your new function:
def new_print(*args, **kwargs):
old_print('print:', *args, **kwargs)
old_print = print
print = new_print

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").

PyQt. Get errors trying to separate GUI from logic

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.

How to change/add chart data series in python-pptx?

I'm trying to set data in an existing chart using python-pptx.
from pptx import Presentation
pres_path = "C:\\pres.pptx"
pres = Presentation(pres_path)
pres.slides[3].shapes[4].chart.series[0].values
(92.0, 330.0, 309.0, 313.0, 356.0, 421.0, 457.0)
pres.slides[3].shapes[4].chart.series[0].values = (1,2,3)
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: can't set attribute
There's a method mentioned in the documentation which seems relevant, but I can't understand how to use it:
http://python-pptx.readthedocs.org/en/latest/_modules/pptx/chart/data.html
pres.slides[3].shapes[4].chart.replace_data((1,2,3))
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Python27\lib\site-packages\pptx\chart\chart.py", line 119, in replace_data
_SeriesRewriter.replace_series_data(self._chartSpace, chart_data)
File "C:\Python27\lib\site-packages\pptx\chart\chart.py", line 197, in replace_series_data
sers = cls._adjust_ser_count(chartSpace, len(chart_data.series))
AttributeError: 'tuple' object has no attribute 'series'
I'd appreciate any help you can provide.
Thanks!
To add a new series to an existing table behind a chart you need to do 3 things:
create an instance of ChartData()
provide category name
add the new series to the ChartData() object, using the "add_series()" func.
chart_data = ChartData()
chart_data.categories = 'category_name'
for col_idx, col in enumerate(single_df.columns):
chart_data.add_series(col, (single_df.ix[:, col_idx].values))
shp.chart.replace_data(chart_data)

Categories

Resources