open command sh and call new window? - python

I'm Italian sorry for my english
I created a plugin, working, now I should be assigned to the yellow - blue keys and information (dreambox enigma2 decoder) command
The blue should run a .sh file in the shell and return to the main menu
the same is true for yellow
the info button it should open a skin, a new information menu .. the closure return to the main menu
*the skin (screen) already includes the buttons drawn
I can not understand the error
here's the listing
class OpenScript(Screen):
skin = '<screen name="main" position="212,15 etc etc >'
def __init__(self, session, args = 0):
Screen.__init__(self, session)
self.session = session
try:
list = listdir('/etc/pandasat/script')
list = [ x[:-3] for x in list if x.endswith('.sh') ]
except:
list = []
#self['key_blue'] = Label(_(' SpeedTest'))
#self['key_yellow'] = Label(_(' Update'))
#self['key_info'] = Label_' Info'))
self['version'] = Label(_('Versione %s' % Version))
self['list'] = MenuList(list)
self['actions'] = ActionMap(['OkCancelActions', 'ColorActions','WizardActions','NumberActions','EPGSelectActions'],{'ok': self.run,
#'key_save': self.run,
'key_exit': self.close,
'red': self.close,
'green': self.run,
#'info': self.ShowAbout,
#'yellow: self.update,
#'blue': self.speedtest,
'cancel': self.close}, -1)
def run(self):
script = self['list'].getCurrent()
if script is not None:
self.session.open(Console, script.replace('_', ' '), cmdlist=['/script/%s.sh' % script])
return
#def speedtest(self): ????????
#def update(self): ?????
#class AboutScreen(Screen):
# skin = '<screen name="InFo" etc etc etc </screen>'
#
Tank' master

Related

Adding Label to Frame tkinter

I am trying to be able to display labels that are tied to a frame. I am unable to get either to show. There is something going on because packing or adding these changes the window size.
Main creates the main app, from which I create several frames that would belong to server objects. When servers are updated, they should reflect the change in the frames (and the labels attached to those frames) that are their respective attributes. However neither the frame nor labels display any text or color.
main.py
from settings.gui_settings import GLOBAL_FONT, SERVER_HEADER_COLUMN_FONT
from tkinter import *
from server import Server
from server_gui import ServerGui
SERVERS = []
# get_servers()
SERVERS = [
Server(hostname='tyan-a320-1', ipv4='10.86.201.3', bmc_ipv4='10.86.203.88'),
Server(hostname='tyan-a320-2', ipv4='10.86.201.91', bmc_ipv4='10.86.202.250'),
Server(hostname='tyan-a320-3', ipv4='10.86.201.13', bmc_ipv4='10.86.201.2'),
Server(hostname='tyan-a320-4', ipv4='10.86.201.50', bmc_ipv4='10.86.200.243'),
]
main_window = Tk()
for server in SERVERS:
server.gui = ServerGui(main_window)
server.gui.create_label('title', textvariable=server.hostname, font=(GLOBAL_FONT, SERVER_HEADER_COLUMN_FONT),\
bg='red', container=True)
server.gui.labels['title'].pack()
server.gui.pack()
#server.update()
last_update_lbl = Label(master=main_window, text=f'Last Update: {time.ctime()}')
last_update_lbl.pack(side=TOP)
#main_window.update()
main_window.mainloop()
server.py
from settings.gui_settings import UP_COLOR, DOWN_COLOR
from diagnostics import poll
from diagnostics import ping
from diagnostics import SERVICES
class Server:
def __init__(self, *args, **kwargs):
for k, v in kwargs.items():
self.__setattr__(k, v)
self.services = {}
for service in SERVICES:
self.services[service] = None
def update(self):
address = None
for service in self.services.keys():
if 'bmc' in service:
address = self.bmc_ipv4
else:
address = self.ipv4
result = None
if service == 'icmp':
result = ping(address)
else:
result = poll(address, SERVICES[service])
if result:
self.services[service] = f'{service}: UP'
else:
self.services[service] = f'{service}: DOWN'
if hasattr(self, 'gui'):
self.gui.update_label(service, 'textvariable', self.services[service])
self.gui.update_label(service, 'bg', UP_COLOR if 'UP' in self.services[service] else DOWN_COLOR)
self.gui.master.update()
server_gui.py
from tkinter import Frame, Label, StringVar
class ServerGui(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.labels = {}
def create_label(self, name, **kwargs):
if not len(name):
print("Label not named")
exit(0)
text = None
label = Label(self)
for k, v in kwargs.items():
if k == 'textvariable':
text = StringVar(master=label, value=v)
label.textvariable = text
else:
label.__setattr__(k, v)
if 'bg' not in kwargs.keys():
label.bg = LABEL_DEFAULT_COLOR
if not text:
text = StringVar(master=label, value=name)
self.labels[name] = label
self.labels[name].pack()
print('Label %s created' % name)
def update_label(self, name, attr, value):
if name not in self.labels:
self.create_label(name,
textvariable=StringVar(self, f'{name}'),
font=(GLOBAL_FONT, SERVER_INFO_FONT),
padx=10,
pady=10
)
self.labels[name].pack()
if attr == 'textvariable':
self.labels[name].textvariable.set(value)
else:
setattr(self.labels[name], attr, value)
settings/gui_settings.py
MAIN_WINDOW_MIN_WIDTH = 700
GLOBAL_FONT = 'Tahoma'
SERVER_HEADER_COLUMN_FONT = 20
SERVER_INFO_FONT = 12
UP_COLOR = 'green'
DOWN_COLOR = 'red'
LABEL_DEFAULT_COLOR = 'green'

LED matrix on Raspberry PI multi-line?

I have a python script but i want to add more lines. How can I go about doing this?
#!/usr/bin/env python
# Display a runtext with double-buffering.
from samplebase import SampleBase
from rgbmatrix import graphics
import time
class RunText(SampleBase):
def __init__(self, *args, **kwargs):
super(RunText, self).__init__(*args, **kwargs)
self.parser.add_argument("-t", "--text", help="The text to scroll on the RGB LED panel", default="I love you!")
def run(self):
offscreen_canvas = self.matrix.CreateFrameCanvas()
font = graphics.Font()
font.LoadFont("../../../fonts/7x13.bdf")
textColor = graphics.Color(255, 255, 0)
pos = offscreen_canvas.width
my_text = self.args.text
while True:
offscreen_canvas.Clear()
len = graphics.DrawText(offscreen_canvas, font, pos, 10, textColor, my_text)
pos -= 1
if (pos + len < 0):
pos = offscreen_canvas.width
time.sleep(0.05)
offscreen_canvas = self.matrix.SwapOnVSync(offscreen_canvas)
# Main function
if __name__ == "__main__":
run_text = RunText()
if (not run_text.process()):
run_text.print_help()
I tried adding another self.parser.add_argument but that did not work.
#!/usr/bin/env python
# Display a runtext with double-buffering.
from samplebase import SampleBase
from rgbmatrix import graphics
import time
class RunText(SampleBase):
def __init__(self, *args, **kwargs):
super(RunText, self).__init__(*args, **kwargs)
self.parser.add_argument("-t", "--text", help="The text to scroll on the RGB LED panel", default="I love you!")
self.parser.add_argument("-t", "--text", help="The text to scroll on the RGB LED panel", default="Will you marry me?")
def run(self):
offscreen_canvas = self.matrix.CreateFrameCanvas()
font = graphics.Font()
font.LoadFont("../../../fonts/7x13.bdf")
textColor = graphics.Color(255, 255, 0)
pos = offscreen_canvas.width
my_text = self.args.text
while True:
offscreen_canvas.Clear()
len = graphics.DrawText(offscreen_canvas, font, pos, 10, textColor, my_text)
pos -= 1
if (pos + len < 0):
pos = offscreen_canvas.width
time.sleep(0.05)
offscreen_canvas = self.matrix.SwapOnVSync(offscreen_canvas)
# Main function
if __name__ == "__main__":
run_text = RunText()
if (not run_text.process()):
run_text.print_help()
This gave me an error output:
Traceback (most recent call last):
argparse.ArgumentError: argument -t/--text: conflicting option string(s): -t, --text
What do I need to fix to get this to have multiple lines? I have tried googling this but am unable to find a solution.
I am using an adafruit hat bonnet with a 128x32 LED panel.
You have to uses only one add_argument("-t", ...) and then you options
1) send all as one string
--text "line1;line2;line3"
and later uses split(";") to split it into lines
2) uses action="append"
add_argument("-t", "--text", action="append")
and then you can uses --text many times and it will create list with all values
--text "line1" --text "line2" --text "line3"
3) uses nargs="*"
add_argument("-t", "--text", nargs="*")
and then you can uses one --text with many lines without ; but using space
--text "line1" "line2" "line3"
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-t1')
parser.add_argument('-t2', action='append')
parser.add_argument('-t3', nargs='*')
args = parser.parse_args()
if args.t1:
args.t1 = args.t1.split(';')
print(args)
Use
./main.py -t1 "a;b;c" -t2 "x" -t2 "y" -t2 "z" -t3 "1" "2" "3"
Result
Namespace(t1=['a', 'b', 'c'], t2=['x', 'y', 'z'], t3=['1', '2', '3'])

Transition between different QListView display options (With CheckBoxes or not) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
With this application, I tried to create 2 variants of the QListView view and apply different ways of working with it. The first option involves a list without Checkboxes, where the user can select several items while holding down the CTRL key:Variant 1. The second option differs visually from the first - checkboxes are present, and the selection process is also different (you do not need to use CTRL, and clicking on a specific position first selects it and then deselects it)Variant 1.
#!/usr/bin/python
# coding=utf-8
headline = """
###############################################################################
# Program #
# a small ListView application in PyQt5 (Python 3.7) #
###############################################################################
All comments are in two languages (Russian, English)
Все комментарии на двух языках (русский, английский)
"""
import sys
import random
from PyQt5 import QtWidgets, QtGui, QtCore, Qt
class HelloApplication(QtWidgets.QApplication):
def __init__(self, args):
"""
In the constructor, we do everything that is necessary to run our application, which
            creates a QApplication in the __init__ method, then adds our widgets and finally
            runs exec_loop
В конструкторе мы делаем всё, что необходимо для запуска нашего приложения, которое
создаёт QApplication в __init__ методе, затем добавляет наши виджеты и, наконец,
запускает exec_loop
"""
QtWidgets.QApplication.__init__(self,args)
self.addWidgets()
def addWidgets(self):
# Create widgets
# Создание виджетов
self.checkCalc=0
self.StartList=[]
self.BaseWidget=QtWidgets.QWidget()
self.BaseWidget.setWindowTitle('Example List')
self.grid = QtWidgets.QGridLayout()
self.verCombo = QtWidgets.QComboBox()
self.listView=QtWidgets.QListView()
self.listViewmodel = QtGui.QStandardItemModel(self.listView)
self.listView.setModel(self.listViewmodel)
# Setting options for widgets (placement, size)
# Установка параметров для виджетов (размещение, размеры)
self.listView.setModelColumn(2)
self.grid.addWidget(self.verCombo,0,0,1,3)
self.grid.addWidget(self.listView, 2, 0, 3, 3)
# Setting actions for widgets
# Установка действий для виджетов
self.listView.clicked[QtCore.QModelIndex].connect(self.on_clicked)
self.verCombo.activated[str].connect(self.onverComboActivated)
# Setting statuses, texts, etc. for widgets at start
# Установка статусов, текстов и прочего для виджетов на старте
self.verCombo.addItem("1 - NO CKECKBOXES")
self.verCombo.addItem("2 - WITH CKECKBOXES")
self.verCombo.setCurrentIndex(0)
# This piece of code determines whether multiple items can be selected on a ListView.
# Этот кусочек кода определяет, можно ли выбирать несколько элементов на ListView.
if self.verCombo.currentIndex() + 1 == 1:
self.listView.setSelectionMode(
QtWidgets.QAbstractItemView.ExtendedSelection
)
#self.show_hide_ckeckinlistView(FType=1)
else:
self.listView.setSelectionMode(
QtWidgets.QAbstractItemView.SingleSelection
)
self.addrowinlistView(
'Cookie dough', # Must be store-bought
'Hummus', # Must be homemade
'Spaghetti', # Must be saucy
'Dal makhani', # Must be spicy
'Chocolate whipped cream' # Must be plentiful
)
self.BaseWidget.setLayout(self.grid)
chechAllSelected_resulr1, chechAllSelected_resulr2, chechAllSelected_resulr3, chechAllSelected_resulr4 = self.chechAllSelected()
self.BaseWidget.show()
# Procedure for determining those items that are highlighted
# The procedure should work both in the situation of the list with checkmarks, and without them
# Процедура для определения тех элементов, которые выделены
# Процедура должна работать как в ситуации списка с галочками, так и без них
def chechAllSelected (self):
SelectedList=[]
list_of_indexes_selectedLayers=[]
list_of_texts_selectedLayers=[]
Items_list=[]
#item = self.listView.itemFromIndex()
selectedLayers = self.listView.selectedIndexes()
# CUT FOR A SHEET WITHOUT TYPES
# ОТЛАВЛИВАЕМ ДЛЯ ЛИСТА БЕЗ ГАЛОЧЕК
if self.verCombo.currentIndex()+1==1:
print ("Here when checking")
for i in selectedLayers:
item = self.listViewmodel.itemFromIndex(i)
Items_list.append(item)
list_of_indexes_selectedLayers.append(item.index().row())
list_of_indexes_selectedLayers.sort()
for i in range(len(list_of_indexes_selectedLayers)):
SelectedList.append(int(list_of_indexes_selectedLayers[i]))
item = self.listViewmodel.itemFromIndex(
self.listViewmodel.index(int(list_of_indexes_selectedLayers[i]), 0))
list_of_texts_selectedLayers.append(item.text())
print("List: ", list_of_indexes_selectedLayers, " ", list_of_texts_selectedLayers, " ", Items_list)
# CUT FOR A SHEET WITH TIPS
# ОТЛАВЛИВАЕМ ДЛЯ ЛИСТА С ГАЛОЧКАМИ
else:
for i in range(self.listViewmodel.rowCount()):
if self.listViewmodel.item(i).checkState():
SelectedList.append(i)
if len(SelectedList)==0: res_chechAllSelected=0
if 0<len(SelectedList)<self.listViewmodel.rowCount(): res_chechAllSelected=1
if 0<len(SelectedList) == self.listViewmodel.rowCount(): res_chechAllSelected = 2
print ("In chechAllSelected:", len(SelectedList)," ", self.listViewmodel.rowCount()," ", res_chechAllSelected, " ", SelectedList)
return len(SelectedList), self.listViewmodel.rowCount(), res_chechAllSelected, SelectedList
# Function for entering values in ListView (any values, lists)
# Функция ввода значений в ListView (любые значения, списки)
def addrowinlistView(self,*rowsforadd):
for i in rowsforadd:
# Create an item with a caption
item = QtGui.QStandardItem(i)
# Add a checkbox to it
#item.setCheckState(True)
# generate a list for random selection
# генерируем список для случайного выбора
Chous_for_random = [0, 2]
if self.verCombo.currentIndex() + 1 == 1:
#print("индекс переключателя: ",self.verCombo.currentIndex() + 1)
# whether to tick the item
# ставить ли галочку около элемента
item.setCheckable(False)
self.listViewmodel.appendRow(item)
if random.choice(Chous_for_random)==2:
index = self.listViewmodel.indexFromItem(item)
sm = self.listView.selectionModel()
sm.select(index, QtCore.QItemSelectionModel.Select)
else:
# whether to tick the item
# ставить ли галочку около элемента
item.setCheckable(True)
# set the status depending on the selected number
# ставим статус в зависимости от выбранного числа
item.setCheckState(random.choice(Chous_for_random))
self.listViewmodel.appendRow(item)
# Add the item to the model
# Добавляем элемент в модель
#self.listViewmodel.appendRow(item)
#self.BaseWidget.listViewmodel.appendRow(item)
def on_clicked(self, index):
item = self.listViewmodel.itemFromIndex(index)
myitem=QtWidgets.QListWidgetItem()
#print (("on_clicked: itemIndex='{}', itemText='{}'"
# .format(item.index().row(), item.text())))
if self.verCombo.currentIndex()+1==1:
# print(item.index().row())
pass
else:
print("""This position: """, int(item.index().row()))
chechAllSelected_resulr1, chechAllSelected_resulr2, chechAllSelected_resulr3, chechAllSelected_resulr4 = self.chechAllSelected()
self.StartList = chechAllSelected_resulr4
if self.listViewmodel.item(item.index().row()).checkState():
item.setCheckState(0)
self.StartList.remove(item.index().row())
else:
item.setCheckState(2)
self.StartList.append(item.index().row())
print("Here")
chechAllSelected_resulr1, chechAllSelected_resulr2, chechAllSelected_resulr3, chechAllSelected_resulr4 = self.chechAllSelected()
#print("Here")
#self.on_chechBox_click(FType=False, FClick=0, FStatus=chechAllSelected_resulr3)
#self.chechAllSelected()
#self.listViewmodel.removeRow(item.index().row())
# mode switching (with / without checkmarks) with the removal of the function to remove / show checkmarks
# перевлючение режима (с галочками / без) с вывозом функции убрать / показать галочки
def onverComboActivated(self, text):
self.verCombo.setCurrentText(text)
len_SelectedList, listViewmodel_rowCount, res_chechAllSelected, SelectedLis = self.chechAllSelected()
print ("This point: ", len_SelectedList," ", listViewmodel_rowCount," ", res_chechAllSelected," ", SelectedLis)
self.show_hide_ckeckinlistView(
self.verCombo.currentIndex(),
listViewmodel_rowCount,
SelectedLis
)
print(self.verCombo.currentText())
# print(self.verCombo.currentText()," индекс = ", self.verCombo.currentIndex())
# self.chechAllSelected ()
if __name__ == "__main__":
app = HelloApplication(sys.argv)
sys.exit(app.exec_())
QAbstractItemView Class
selectionMode : SelectionMode
This property holds which selection mode the view operates in
This property controls whether the user can select one or many items and, in many-item selections,
whether the selection must be a continuous range of items.
QAbstractItemView::ExtendedSelection
When the user selects an item in the usual way, the selection is cleared and the new item selected.
However, if the user presses the Ctrl key when clicking on an item, the clicked item gets toggled
and all other items are left untouched. If the user presses the Shift key while clicking on an item,
all items between the current item and the clicked item are selected or unselected, depending
on the state of the clicked item. Multiple items can be selected by dragging the mouse over them.
Try it:
headline = """
###############################################################################
# Program #
# a small ListView application in PyQt #
###############################################################################
"""
import sys
import random
from PyQt5 import QtWidgets, QtGui, QtCore # , Qt
class HelloApplication(QtWidgets.QWidget): #QApplication):
def __init__(self):
super().__init__()
self.addWidgets()
def addWidgets(self):
self.checkCalc = 0
self.StartList = []
# self.BaseWidget = QtWidgets.QWidget()
self.setWindowTitle('Example List')
self.grid = QtWidgets.QGridLayout()
self.verCombo = QtWidgets.QComboBox()
self.listView = QtWidgets.QListView()
# +++
self.listView.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection) # +++
self.listViewmodel = QtGui.QStandardItemModel(self.listView)
self.listView.setModel(self.listViewmodel)
self.listView.setModelColumn(2)
self.grid.addWidget(self.verCombo, 0, 0, 1, 3)
self.grid.addWidget(self.listView, 2, 0, 3, 3)
self.listView.clicked[QtCore.QModelIndex].connect(self.on_clicked)
self.verCombo.activated[str].connect(self.onverComboActivated)
self.verCombo.addItem("1 - NO edit CKECKBOXES")
self.verCombo.addItem("2 - WITH edit CKECKBOXES")
self.verCombo.setCurrentIndex(0)
self.addrowinlistView(
'Cookie dough', # Must be store-bought
'Hummus', # Must be homemade
'Spaghetti', # Must be saucy
'Dal makhani', # Must be spicy
'Chocolate whipped cream' # Must be plentiful
)
self.setLayout(self.grid)
chechAllSelected_resulr1, \
chechAllSelected_resulr2, \
chechAllSelected_resulr3, \
chechAllSelected_resulr4 = self.chechAllSelected()
def chechAllSelected (self):
SelectedList = []
list_of_indexes_selectedLayers = []
list_of_texts_selectedLayers = []
Items_list = []
#item = self.listView.itemFromIndex()
selectedLayers = self.listView.selectedIndexes()
if self.verCombo.currentIndex()+1 == 1:
print ("Here for check")
for i in selectedLayers:
item = self.listViewmodel.itemFromIndex(i)
Items_list.append(item)
list_of_indexes_selectedLayers.append(item.index().row())
list_of_indexes_selectedLayers.sort()
for i in range(len(list_of_indexes_selectedLayers)):
SelectedList.append(int(list_of_indexes_selectedLayers[i]))
item = self.listViewmodel.itemFromIndex(
self.listViewmodel.index(int(list_of_indexes_selectedLayers[i]), 0))
list_of_texts_selectedLayers.append(item.text())
print("List: ", list_of_indexes_selectedLayers, " ", list_of_texts_selectedLayers, " ", Items_list)
else:
for i in range(self.listViewmodel.rowCount()):
if self.listViewmodel.item(i).checkState():
SelectedList.append(i)
if len(SelectedList)==0: res_chechAllSelected = 0
if 0<len(SelectedList)<self.listViewmodel.rowCount(): res_chechAllSelected = 1
if 0<len(SelectedList) == self.listViewmodel.rowCount(): res_chechAllSelected = 2
print ("В модуле chechAllSelected:", len(SelectedList)," ", self.listViewmodel.rowCount()," ", res_chechAllSelected, " ", SelectedList)
return len(SelectedList), self.listViewmodel.rowCount(), res_chechAllSelected, SelectedList
def addrowinlistView(self, *rowsforadd):
for i in rowsforadd:
# Create an item with a caption
item = QtGui.QStandardItem(i)
# Add a checkbox to it
item.setCheckState(True) # +
Chous_for_random = [0, 2]
if self.verCombo.currentIndex() + 1 == 1:
#print("индекс переключателя: ",self.verCombo.currentIndex() + 1)
item.setCheckable(False)
self.listViewmodel.appendRow(item)
if random.choice(Chous_for_random)==2:
index = self.listViewmodel.indexFromItem(item)
sm = self.listView.selectionModel()
sm.select(index, QtCore.QItemSelectionModel.Select)
else:
item.setCheckable(True)
item.setCheckState(random.choice(Chous_for_random))
self.listViewmodel.appendRow(item)
# Add the item to the model
#self.listViewmodel.appendRow(item)
#self.BaseWidget.listViewmodel.appendRow(item)
def on_clicked(self, index):
item = self.listViewmodel.itemFromIndex(index)
print(f"\nitem={item.text()}, index={index.row()}\n" )
myitem = QtWidgets.QListWidgetItem()
#print (("on_clicked: itemIndex='{}', itemText='{}'"
# .format(item.index().row(), item.text())))
if self.verCombo.currentIndex()+1 == 1:
# print(item.index().row())
pass
else:
print("This position: ", int(item.index().row()))
chechAllSelected_resulr1, chechAllSelected_resulr2, chechAllSelected_resulr3, chechAllSelected_resulr4 = self.chechAllSelected()
self.StartList = chechAllSelected_resulr4
if self.listViewmodel.item(item.index().row()).checkState():
item.setCheckState(0)
self.StartList.remove(item.index().row())
else:
item.setCheckState(2)
self.StartList.append(item.index().row())
print("Now here")
chechAllSelected_resulr1, chechAllSelected_resulr2, chechAllSelected_resulr3, chechAllSelected_resulr4 = self.chechAllSelected()
#print("Now here")
#self.on_chechBox_click(FType=False, FClick=0, FStatus=chechAllSelected_resulr3)
#self.chechAllSelected()
#self.listViewmodel.removeRow(item.index().row())
def onverComboActivated(self, text):
self.verCombo.setCurrentText(text)
len_SelectedList, listViewmodel_rowCount, res_chechAllSelected, SelectedLis = self.chechAllSelected()
print ("\nFor print: \n\tlen_SelectedList = {}; \n\tlistViewmodel_rowCount = {};\
\n\tres_chechAllSelected = {}; \n\tSelectedLis = {}"
"".format(len_SelectedList, listViewmodel_rowCount, res_chechAllSelected, SelectedLis))
# ? self.show_hide_ckeckinlistView(
# self.verCombo.currentIndex(),
# listViewmodel_rowCount,
# SelectedLis
# )
print(self.verCombo.currentText())
# print(self.verCombo.currentText()," индекс = ", self.verCombo.currentIndex())
# self.chechAllSelected ()
""" ??????????????????????????????????????????????????
def on_clicked(self, index):
item = self.listViewmodel.itemFromIndex(index)
myitem=QtWidgets.QListWidgetItem()
#print (("on_clicked: itemIndex='{}', itemText='{}'"
# .format(item.index().row(), item.text())))
if self.verCombo.currentIndex()+1==1:
# print(item.index().row())
pass
else:
print("This position: ", int(item.index().row()))
chechAllSelected_resulr1, chechAllSelected_resulr2, chechAllSelected_resulr3, chechAllSelected_resulr4 = self.chechAllSelected()
self.StartList = chechAllSelected_resulr4
if self.listViewmodel.item(item.index().row()).checkState():
item.setCheckState(0)
self.StartList.remove(item.index().row())
else:
item.setCheckState(2)
self.StartList.append(item.index().row())
print("Now here")
#chechAllSelected_resulr1, chechAllSelected_resulr2, chechAllSelected_resulr3, chechAllSelected_resulr4 = self.chechAllSelected()
print("Now here")
#self.on_chechBox_click(FType=False, FClick=0, FStatus=chechAllSelected_resulr3)
#self.chechAllSelected()
#self.listViewmodel.removeRow(item.index().row())
"""
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = HelloApplication()
w.show()
sys.exit(app.exec_())

Python for Robotics: How to generate an app for localization of a Pepper robot

These days I have tried to generate an application using the pythonapp template from the Github project Jumpstarter(https://github.com/aldebaran/robot-jumpstarter) to do the localization of Pepper. My basic idea is to combine the LandmarkDetector module in the generated app „Lokalisierung“(Localization of German).
You can read the whole code of "LandmarkDetector.py","main.py" and"MainLandmarkDetection.py" here:
"LandmarkDetector.py":
#! /usr/bin/env python
# -*- encoding: UTF-8 -*-
"""Example: Demonstrates a way to localize the robot with
ALLandMarkDetection"""
import qi
import time
import sys
import argparse
import math
import almath
class LandmarkDetector(object):
"""
We first instantiate a proxy to the ALLandMarkDetection module
Note that this module should be loaded on the robot's naoqi.
The module output its results in ALMemory in a variable
called "LandmarkDetected".
We then read this ALMemory value and check whether we get
interesting things.
After that we get the related position of the landmark compared to robot.
"""
def __init__(self, app):
"""
Initialisation of qi framework and event detection.
"""
super(LandmarkDetector, self).__init__()
app.start()
session = app.session
# Get the service ALMemory.
self.memory = session.service("ALMemory")
# Connect the event callback.
# Get the services ALMotion & ALRobotPosture.
self.motion_service = session.service("ALMotion")
self.posture_service = session.service("ALRobotPosture")
self.subscriber = self.memory.subscriber("LandmarkDetected")
print "self.subscriber = self.memory.subscriber(LandmarkDetected)"
self.subscriber.signal.connect(self.on_landmark_detected)
print "self.subscriber.signal.connect(self.on_landmark_detected)"
# Get the services ALTextToSpeech, ALLandMarkDetection and ALMotion.
self.tts = session.service("ALTextToSpeech")
self.landmark_detection = session.service("ALLandMarkDetection")
# print "self.landmark_detection" is repr(self.landmark_detection)
self.motion_service = session.service("ALMotion")
self.landmark_detection.subscribe("LandmarkDetector", 500, 0.0 )
print "self.landmark_detection.subscribe(LandmarkDetector, 500, 0.0 )"
self.got_landmark = False
# Set here the size of the landmark in meters.
self.landmarkTheoreticalSize = 0.06 #in meters 0 #.05 or 0.06?
# Set here the current camera ("CameraTop" or "CameraBottom").
self.currentCamera = "CameraTop"
def on_landmark_detected(self, markData):
"""
Callback for event LandmarkDetected.
"""
while markData == [] : # empty value when the landmark disappears
self.got_landmark = False
self.motion_service.moveTo(0, 0, 0.1 * math.pi)
if not self.got_landmark: # only speak the first time a landmark appears
self.got_landmark = True
#stop.motion_service.moveTo
print "Ich sehe eine Landmarke! "
self.tts.say("Ich sehe eine Landmarke! ")
# Retrieve landmark center position in radians.
wzCamera = markData[1][0][0][1]
wyCamera = markData[1][0][0][2]
# Retrieve landmark angular size in radians.
angularSize = markData[1][0][0][3]
# Compute distance to landmark.
distanceFromCameraToLandmark = self.landmarkTheoreticalSize / ( 2 * math.tan( angularSize / 2))
# Get current camera position in NAO space.
transform = self.motion_service.getTransform(self.currentCamera, 2, True)
transformList = almath.vectorFloat(transform)
robotToCamera = almath.Transform(transformList)
# Compute the rotation to point towards the landmark.
cameraToLandmarkRotationTransform = almath.Transform_from3DRotation(0, wyCamera, wzCamera)
# Compute the translation to reach the landmark.
cameraToLandmarkTranslationTransform = almath.Transform(distanceFromCameraToLandmark, 0, 0)
# Combine all transformations to get the landmark position in NAO space.
robotToLandmark = robotToCamera * cameraToLandmarkRotationTransform *cameraToLandmarkTranslationTransform
# robotTurnAroundAngle = almath.rotationFromAngleDirection(0, 1, 1, 1)
# print "robotTurnAroundAngle = ", robotTurnAroundAngle
print "x " + str(robotToLandmark.r1_c4) + " (in meters)"
print "y " + str(robotToLandmark.r2_c4) + " (in meters)"
print "z " + str(robotToLandmark.r3_c4) + " (in meters)"
def run(self):
"""
Loop on, wait for events until manual interruption.
"""
# Wake up robot
self.motion_service.wakeUp()
# Send robot to Pose Init
self.posture_service.goToPosture("StandInit", 0.5)
# Example showing how to get a simplified robot position in world.
useSensorValues = False
result = self.motion_service.getRobotPosition(useSensorValues)
print "Robot Position", result
# Example showing how to use this information to know the robot's diplacement.
useSensorValues = False
# initRobotPosition = almath.Pose2D(self.motion_service.getRobotPosition(useSensorValues))
# Make the robot move
for i in range(1, 12, 1):
self.motion_service.moveTo(0, 0, 0.1 * math.pi)
print "self.motion_service.moveTo(0, 0, (0.1)*math.pi)"
print "Starting LandmarkDetector"
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print "Interrupted by user, stopping LandmarkDetector"
self.landmark_detection.unsubscribe("LandmarkDetector")
#stop
sys.exit(0)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--ip", type=str, default="10.0.0.10",
help="Robot IP address. On robot or Local Naoqi: use
'10.0.0.10'.")
parser.add_argument("--port", type=int, default=9559,
help="Naoqi port number")
args = parser.parse_args()
try:
# Initialize qi framework.
connection_url = "tcp://" + args.ip + ":" + str(args.port)
app = qi.Application(["LandmarkDetector", "--qi-url=" + connection_url])
except RuntimeError:
print ("Can't connect to Naoqi at ip \"" + args.ip + "\" on port " + str(args.port) +".\n"
"Please check your script arguments. Run with -h option for help.")
sys.exit(1)
landmark_detector = LandmarkDetector(app)
landmark_detector.run()
"main.py":
""" A sample showing how to make a Python script as an app. """
version = "0.0.8"
copyright = "Copyright 2015, Aldebaran Robotics"
author = 'YOURNAME'
email = 'YOUREMAIL#aldebaran.com'
import stk.runner
import stk.events
import stk.services
import stk.logging
class Activity(object):
"A sample standalone app, that demonstrates simple Python usage"
APP_ID = "com.aldebaran.lokalisierung"
def __init__(self, qiapp):
self.qiapp = qiapp
self.events = stk.events.EventHelper(qiapp.session)
self.s = stk.services.ServiceCache(qiapp.session)
self.logger = stk.logging.get_logger(qiapp.session, self.APP_ID)
def on_touched(self, *args):
"Callback for tablet touched."
if args:
self.events.disconnect("ALTabletService.onTouchDown")
self.logger.info("Tablet touched: " + str(args))
self.s.ALTextToSpeech.say("Yay!")
self.stop()
def on_start(self):
"Ask to be touched, waits, and exits."
# Two ways of waiting for events
# 1) block until it's called
self.s.ALTextToSpeech.say("Touch my forehead.")
self.logger.warning("Listening for touch...")
while not self.events.wait_for("FrontTactilTouched"):
pass
# 2) explicitly connect a callback
if self.s.ALTabletService:
self.events.connect("ALTabletService.onTouchDown", self.on_touched)
self.s.ALTextToSpeech.say("okay, now touch my tablet.")
# (this allows to simltaneously speak and watch an event)
else:
self.s.ALTextToSpeech.say("touch my tablet ... oh. " + \
"I don't haave one.")
self.stop()
def stop(self):
"Standard way of stopping the application."
self.qiapp.stop()
def on_stop(self):
"Cleanup"
self.logger.info("Application finished.")
self.events.clear()
if __name__ == "__main__":
stk.runner.run_activity(Activity)
"MainLandmarkDetection.py":
#! /usr/bin/env python
# -*- encoding: UTF-8 -*-
"""A sample showing how to make a Python script as an app to localize
the robot with ALLandMarkDetection"""
version = "0.0.8"
copyright = "Copyright 2015, Aldebaran Robotics"
author = 'YOURNAME'
email = 'YOUREMAIL#aldebaran.com'
import stk.runner
import stk.events
import stk.services
import stk.logging
import time
import sys
import math
import almath
class Activity(object):
"A sample standalone app, that demonstrates simple Python usage"
APP_ID = "com.aldebaran.lokalisierung"
def __init__(self, qiapp):
self.qiapp = qiapp
self.events = stk.events.EventHelper(qiapp.session)
self.s = stk.services.ServiceCache(qiapp.session)
self.logger = stk.logging.get_logger(qiapp.session, self.APP_ID)
self.qiapp.start()
session = qiapp.session
# Get the service ALMemory.
self.memory = session.service("ALMemory")
# Connect the event callback.
# Get the services ALMotion & ALRobotPosture.
self.motion_service = session.service("ALMotion")
self.posture_service = session.service("ALRobotPosture")
self.subscriber = self.memory.subscriber("LandmarkDetected")
print "self.subscriber = self.memory.subscriber(LandmarkDetected)"
self.subscriber.signal.connect(self.on_landmark_detected)
print "self.subscriber.signal.connect(self.on_landmark_detected)"
# Get the services ALTextToSpeech, ALLandMarkDetection and ALMotion.
self.tts = session.service("ALTextToSpeech")
self.landmark_detection = session.service("ALLandMarkDetection")
# print "self.landmark_detection" is repr(self.landmark_detection)
self.motion_service = session.service("ALMotion")
self.landmark_detection.subscribe("Activity", 500, 0.0)
print "self.landmark_detection.subscribe(Activity, 500, 0.0 )"
self.got_landmark = False
# Set here the size of the landmark in meters.
self.landmarkTheoreticalSize = 0.06 # in meters 0 #.05 or 0.06?
# Set here the current camera ("CameraTop" or "CameraBottom").
self.currentCamera = "CameraTop"
def on_landmark_detected(self, markData):
"""
Callback for event LandmarkDetected.
"""
while markData == []: # empty value when the landmark disappears
self.got_landmark = False
# self.motion_service.moveTo(0, 0, 0.1 * math.pi)
if not self.got_landmark: # only speak the first time a landmark appears
self.got_landmark = True
# stop.motion_service.moveTo
print "Ich sehe eine Landmarke! "
# self.tts.say("Ich sehe eine Landmarke! ")
# Retrieve landmark center position in radians.
wzCamera = markData[1][0][0][1]
wyCamera = markData[1][0][0][2]
# Retrieve landmark angular size in radians.
angularSize = markData[1][0][0][3]
# Compute distance to landmark.
distanceFromCameraToLandmark = self.landmarkTheoreticalSize / (2 * math.tan(angularSize / 2))
# Get current camera position in NAO space.
transform = self.motion_service.getTransform(self.currentCamera, 2, True)
transformList = almath.vectorFloat(transform)
robotToCamera = almath.Transform(transformList)
# Compute the rotation to point towards the landmark.
cameraToLandmarkRotationTransform = almath.Transform_from3DRotation(0, wyCamera, wzCamera)
# Compute the translation to reach the landmark.
cameraToLandmarkTranslationTransform = almath.Transform(distanceFromCameraToLandmark, 0, 0)
# Combine all transformations to get the landmark position in NAO space.
robotToLandmark = robotToCamera * cameraToLandmarkRotationTransform * cameraToLandmarkTranslationTransform
# robotTurnAroundAngle = almath.rotationFromAngleDirection(0, 1, 1, 1)
# print "robotTurnAroundAngle = ", robotTurnAroundAngle
print "x " + str(robotToLandmark.r1_c4) + " (in meters)"
print "y " + str(robotToLandmark.r2_c4) + " (in meters)"
print "z " + str(robotToLandmark.r3_c4) + " (in meters)"
def run(self):
"""
Loop on, wait for events until manual interruption.
"""
# Wake up robot
self.motion_service.wakeUp()
# Send robot to Pose Init
self.posture_service.goToPosture("StandInit", 0.5)
# Example showing how to get a simplified robot position in world.
useSensorValues = False
result = self.motion_service.getRobotPosition(useSensorValues)
print "Robot Position", result
# Example showing how to use this information to know the robot's diplacement.
useSensorValues = False
# initRobotPosition = almath.Pose2D(self.motion_service.getRobotPosition(useSensorValues))
# Make the robot move
for i in range(1, 20, 1):
self.motion_service.moveTo(0, 0, 0.1 * math.pi)
print "self.motion_service.moveTo(0, 0, (0.1)*math.pi)"
print "Starting Activity"
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print "Interrupted by user, stopping Activity"
self.landmark_detection.unsubscribe("Activity")
# stop
sys.exit(0)
def stop(self):
"Standard way of stopping the application."
self.qiapp.stop()
def on_stop(self):
"Cleanup"
self.logger.info("Application finished.")
self.events.clear()
if __name__ == "__main__":
stk.runner.run_activity(Activity)
landmark_detector = Activity()
landmark_detector.run()
This is how it worked in cmd.exe:
And I have a question to the parameter by ”landmark_detector = Activity()” in line 157 at almost the end of the program because of the Error in the image, which I should pass. After reading the answers to the similar question here by StackoverflowPython: TypeError: __init__() takes exactly 2 arguments (1 given), I am still confused. I think it should be a value which is given to the "qiapp", but what value?
Best regards,
Frederik
Actually, when you call
stk.runner.run_activity(Activity)
... it will instantiate that activity object for you, with the right parameters, you don't need to landmark_detector = Activity() etc. in MainLandmarkDetector.py
And if this object has a method called on_start, that method will be called once everything is ready (so you may only need to rename your run() method to on_start()
Note also that instead of calling sys.stop(), you can just call self.stop() or self.qiapp.stop() (which is a bit cleaner in terms of letting the cleanup code in on_stop to be called, if you need to unsubscribe to things etc.)
See here for some documentation on stk.runner.
Note also that instead of doing
self.motion_service = session.service("ALMotion")
(...)
transform = self.motion_service.getTransform(self.currentCamera, 2, True)
you can directly do
transform = self.s.ALMotion.getTransform(self.currentCamera, 2, True)
... which (in my opinion) makes it easier to see what is being done exactly (and reduces the number of variables).

PyGTK custom ComboBox behavior

I'm trying to create a custom ComboBox that behaves like the one in here: http://chir.ag/projects/name-that-color/
I've got two problems right now:
I can't seem to find a way to have a scrollbar on the side; the gtk.rc_parse_string function should do that, since the ComboBox widget has a "appears-as-list" style property, but my custom widget seems unaffected for some reason.
When you select a color from my widget, then click the ComboBox again, instead of showing the selected item and its neighbours, the scrolled window starts from the top, for no apparent reason.
This is the code, you can pretty much ignore the __load_name_palette method. You need the /usr/share/X11/rgb.txt file to run this code, it looks like this: http://pastebin.com/raw.php?i=dkemmEdr
import gtk
import gobject
from os.path import exists
def window_delete_event(*args):
return False
def window_destroy(*args):
gtk.main_quit()
class ColorName(gtk.ComboBox):
colors = []
def __init__(self, name_palette_path, wrap_width=1):
gtk.ComboBox.__init__(self)
liststore = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING,
gobject.TYPE_STRING)
name_palette = self.__load_name_palette(name_palette_path)
for c in name_palette:
r, g, b, name = c
if ((r + g + b) / 3.) < 128.:
fg = '#DDDDDD'
else:
fg = '#222222'
bg = "#%02X%02X%02X" % (r, g, b)
liststore.append((name, bg, fg))
self.set_model(liststore)
label = gtk.CellRendererText()
self.pack_start(label, True)
self.set_attributes(label, background=1, foreground=2, text=0)
self.set_wrap_width(wrap_width)
if len(name_palette) > 0:
self.set_active(0)
self.show_all()
def __load_name_palette(self, name_palette_path):
if exists(name_palette_path):
try:
f = open(name_palette_path,'r')
self.colors = []
palette = set()
for l in f:
foo = l.rstrip().split(None,3)
try:
rgb = [int(x) for x in foo[:3]]
name, = foo[3:]
except:
continue
k = ':'.join(foo[:3])
if k not in palette:
palette.add(k)
self.colors.append(rgb + [name])
f.close()
return self.colors
except IOError as (errno, strerror):
print "error: failed to open {0}: {1}".format(name_palette_path, strerror)
return []
else:
return []
if __name__ == '__main__':
win = gtk.Window()
#colname = ColorName('./ntc.txt')
colname = ColorName('/usr/share/X11/rgb.txt')
gtk.rc_parse_string("""style "mystyle" { GtkComboBox::appears-as-list = 1 }
class "GtkComboBox" style "mystyle" """)
print 'appears-as-list:', colname.style_get_property('appears-as-list')
model = gtk.ListStore(gobject.TYPE_STRING)
hbox = gtk.HBox()
win.add(hbox)
hbox.pack_start(colname)
win.connect('delete-event', window_delete_event)
win.connect('destroy', window_destroy)
win.show_all()
gtk.main()
The problem was the self.show_all() line. Also, you can't have a list AND a wrap_width != 1

Categories

Resources