I'm trying to put a line in the header of a QTextTable.
I have tried three ways to do it:
Option 1 - I have used the option to modify the background color of the cell. The problem is, I can't narrow the line.
Option 2 - I insert an Html code, but I cannot modify the properties of the line.
Option 3 - I have created an image, I have drawn a line, but when I put that the length of the line is the width of the page the table deforms. I can see the line in the screen, but not when I print it.
Option 4 - Suggestion of musicamente. Not works because not write a red line, but background is blue, so the format is tranfer.
Option 1
Option 2
Option 3
Option 4
The code is:
from PyQt5.QtWidgets import QApplication ,QWidget
from PyQt5.QtPrintSupport import QPrinter,QPrintPreviewDialog
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QTextDocument,QTextCursor,QPainter,QFont,QImage,QTextTableFormat,QPixmap,QTextLength,QPixmap,QTextBlockFormat,QTextCharFormat,QPen,QTextFrameFormat,QIcon,QColor,QBrush
class QPrint_Table(QWidget):
def __init__(self,table,fields):
super().__init__()
self.table=table
self.fields=fields
self.printer = QPrinter(QPrinter.HighResolution)
dialog = QPrintPreviewDialog()
dialog.paintRequested.connect(self.handlePaintRequest)
dialog.exec_()
def handlePaintRequest(self, printer):
document = self.makeTableDocument()
document.print_(printer)
def makeTableDocument(self):
document = QTextDocument()
cursor = QTextCursor(document)
rows = len(self.table)
columns = len(self.fields)
self.pageSize = self.printer.pageRect().size()
tableFormat = QTextTableFormat()
#tableFormat.setAlignment(QtCore.Qt.AlignRight) # Justify Table
#tableFormat.setBackground(QtGui.QColor('#e0e0e0'))
tableFormat.setCellPadding(4)
tableFormat.setCellSpacing(0)
tableFormat.setBorder(0)
tableFormat.setWidth(QTextLength(QTextLength.PercentageLength, 100))
table_text = cursor.insertTable(rows + 2, columns, tableFormat)
format = table_text.format()
format.setHeaderRowCount(1)
table_text.setFormat(format)
format = cursor.blockCharFormat()
format.setFontWeight(QFont.Bold)
for column in range(columns):
cursor.setCharFormat(format)
cursor.insertText(fields[column])
cursor.movePosition(QTextCursor.NextCell)
table_text.mergeCells(1,0,1,columns)
cell=table_text.cellAt(1,0)
format =cell.format()
line_option=4
if line_option==1:
# Option 1 - For black Line
format =cell.format()
format.setBackground(Qt.black)
cell.setFormat(format)
format_low=cursor.blockCharFormat()
font=QFont ( "Arial" , 0 )
font.setPointSizeF(0.9)
format_low.setFont(font)
cursor.setCharFormat(format_low)
cursor.insertText('.')
elif line_option==2:
# Option 2
cursor.insertHtml('<html> <body> <hr style="height:5px;border-width:3px;color:red;background-color:green"></body> </html>')
elif line_option==3:
# Option 3
height=20
line_width=self.pageSize.width()
image = QImage(line_width,height,QImage.Format_RGB32)
ratio=self.printer.resolution()/60
image.setDevicePixelRatio(ratio)
painter = QPainter(image)
pen = QPen(Qt.red, height*2)
painter.setPen(pen)
painter.drawLine(0, 0, line_width, 0)
cursor.insertImage(image)
painter.end()
elif line_option==4:
# Option 4
format_cell=format.toTableCellFormat()
format_cell.setBackground(Qt.blue)
format_cell.setBorder(100)
format_cell.setBottomBorder(10)
format_cell.setBottomBorderBrush(QBrush(QColor("red")))
cell.setFormat(format_cell)
cursor.movePosition(QTextCursor.NextCell)
for row in range(rows):
for column in range(columns):
cursor.insertText(str(self.table[row][column]))
cursor.movePosition(QTextCursor.NextCell)
return document
def create_table():
list=[]
for i in range(10):
list.append([i,'Name '+str(i),'Address '+str(i),'City '+str(i),'Country '+str(i)])
fields=['Id','Name','Address','City','Country']
return list,fields
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
table,fields=create_table()
QPrint_Table(table,fields)
Related
I have a program that is "divided" in 6 classes, the first class is the Main Window where I can choose where I'd like to go (I have 4 choices, a page to visualize all the data, one to modify and the other 2 to visualize data with filters), each of theese pages is a QDialog that contains a QTableWidget, this table is connected to a SQL Server database and shows data from a specific table (to be honest it shows data from 2 tables).
My problem is:
In the 2 class ("modificaviaggi") I connected some signals to some action, first of all I connected the itemChanged signal to a method that stores the items written by the user and saves them in the SQL DB, the signal signal I used is the clicked signal, I connected this signal to a method that verifies if the cell clicked it's the 8 or 9, in case it's 8 or 9 it shows another QDialog (class "articoli") where the user can insert some data regarding weight of every product, this weight data are stored in a second table in the SQL Server DB, I use this table to get the weight for every product when I show my table.
So I get all the data from the table SQL "Viaggi" and then I verify if there are some values in the SQL table "Pesi" for each row of the table "Viaggi" using the row ID.
Now the complicated part is that when the user click the columns 8 or 9 it shows another Qdialog, I show this Qdialog everytime the user clicks the columns 8 or 9, then the user can write data on the table and those data will be stored in the table "Pesi", thanks to the variable "lastID" declared on the "modificaviggi" class I know for which row the user clicked the columns 8 or 9, thanks to that I store the values in the SQL table and for each value I have their row ID, now that the situation is more clear the real question is: How can "Re-load" the QTableWidget "tabella_registrazioni" inside the class "modificaviaggi" everytime the user clicks the QPushButton "get_back_button"? Because in the class "articoli" the user modifies/adds values for each row in the QTableWidget "tabella_registrazioni" but I can't reload the data inside here's my code :
c = conn.cursor()
d = conndue.cursor()
class Ui(QtWidgets.QMainWindow):
def __init__(self):
super(Ui, self).__init__() # chiamare le inherited classi con metodo __init__
uic.loadUi('pagina_scelta.ui', self) # caricare file.ui
self.show() # mostrarlo
bottonefinestramodifica = self.findChild(QtWidgets.QPushButton, 'bottone_modifica')
bottonefinestramodifica.clicked.connect(self.finestramodifica)
def finestramodifica(self):
self.finestramodifica = modificaviaggi()
self.finestramodifica.show()
class MyDelegate(QStyledItemDelegate):
def createEditor(self, parent, option, index):
return
class modificaviaggi(QtWidgets.QDialog):
lastid = [0]
recall = [2]
def finestraarticoli(self):
self.finestraarticoli = articoli()
self.finestraarticoli.show()
def chiusura(self):
self.accept()
def __init__(self):
super(modificaviaggi, self).__init__()
uic.loadUi('modifica_reg.ui', self)
bottonetorna = self.bottone_torna
bottonetorna.clicked.connect(self.chiusura)
self.reloading()
self.datitabella()
def reloading(self):
if 1 == 1:
if self.recall[0] == 1:
self.datitabella()
self.recall[0] == 2
def datitabella(self):
delegate = MyDelegate(self)
tablerow = 0
conteggio = c.execute('SELECT COUNT(ID) FROM Viaggi').fetchone()[0]
print(conteggio)
customers = [" "]
self.tabella_registrazioni.blockSignals(True)
self.customers_combo(customers)
self.tabella_registrazioni.setRowCount(conteggio)
for row in c.execute("SELECT * FROM Viaggi "):
rigavalore = 0
self.tabella_registrazioni.setRowCount(conteggio)
for r in range(0, 19):
self.tabella_registrazioni.setItem(tablerow, rigavalore, QtWidgets.QTableWidgetItem(str(row[rigavalore])))
rigavalore+= 1
tablerow+= 1
self.combocreation(customers)
self.combocreation(customers)
self.tabella_registrazioni.blockSignals(False)
self.tabella_registrazioni.itemChanged.connect(self.changeIcon)
self.tabella_registrazioni.setItemDelegateForColumn(0, delegate)
self.tabella_registrazioni.clicked.connect(self.pressed)
self.combo_customers.activated.connect(self.customer_combo_selection)
righe = self.tabella_registrazioni.rowCount()
tablerow1= 0
for i in range(0, righe):
idrow = self.tabella_registrazioni.item(i, 0).text()
netweight = c.execute("SELECT SUM(Peso_netto) FROM Pesi WHERE ID_registrazione = ?", idrow)
if netweight != None or not netweight.isspace():
netweight = float(str(netweight.fetchone()[0]))
else:
print("Nessun peso")
grossweight = c.execute("SELECT SUM(Peso_lordo) FROM Pesi WHERE ID_registrazione = ?", idrow)
if grossweight != None or not grossweight.isspace():
grossweight = float(str(grossweight.fetchone()[0]))
self.tabella_registrazioni.setItem(tablerow1, 8, QtWidgets.QTableWidgetItem(str(netweight)))
self.tabella_registrazioni.setItem(tablerow1, 9, QtWidgets.QTableWidgetItem(str(grossweight)))
tablerow1+= 1
def combocreation(self, customers):
self.combo_customers = QComboBox()
self.combo_customers.setEditable(True)
def customers_combo(self, customers):
for cu in d.execute("SELECT ANDESCRI FROM VALL_CONTI WHERE ANTIPCON = 'C' "):
customers.append(cu[0].strip())
def changeIcon(self, item):
row = item.row()
col = item.column()
zero = self.tabella_registrazioni.item(row, 0).text()
uno = self.tabella_registrazioni.item(row, 1).text()
custcode = self.tabella_registrazioni.item(row, 3).text()
custname = self.tabella_registrazioni.item(row, 4).text()
c.execute('UPDATE Viaggi SET Codice_cliente = ?, Ragione_sociale = ? WHERE ID = ?',
(custcode, custname, zero))
c.commit()
def pressed(self, item):
row = item.row()
col = item.column()
customers = [" "]
self.lastid[0] = self.tabella_registrazioni.item(row, 0).text()
if col == 8 or col == 9:
self.finestraarticoli()
self.customers_combo(customers)
self.combocreation(customers)
textcell = self.tabella_registrazioni.item(row, col).text()
self.combo_customers.setCurrentText(textcell)
self.combo_customers.activated.connect(self.customer_combo_selection)
if col == 3:
self.tabella_registrazioni.setCellWidget(row, 3, self.combo_customers)
def customer_combo_selection(self):
customer_name = self.combo_customers.currentText()
row = self.rrow
self.tabella_registrazioni.setItem(self.rrow, self.ccolumn, QtWidgets.QTableWidgetItem(str(customer_name)))
id = self.tabella_registrazioni.item(row, 0).text()
c.execute("UPDATE Viaggi SET Ragione_Sociale=? WHERE ID = ?", (customer_name, id))
c.commit()
class articoli(QtWidgets.QDialog):
def changevariable(self):
modificaviaggi.recall[0] = 1
self.accept()
def __init__(self):
super(articoli, self).__init__()
uic.loadUi('Inserimento_articoli.ui', self)
self.get_back_button.clicked.connect(self.changevariable)
self.tabellapesi()
def tabellapesi(self):
self.IDpressed = modificaviaggi.lastid
tablerow = 0
self.tabella_articoli.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
self.conteggio = int(str(c.execute("SELECT COUNT(ID_registrazione) FROM Pesi WHERE ID_registrazione = ? ", self.IDpressed[0]).fetchone()[0]))
for row in c.execute("SELECT * FROM Pesi WHERE ID_registrazione = ? ORDER BY ID ", self.IDpressed[0]):
rigavalore = 0
self.tabella_articoli.setRowCount(self.conteggio)
for r in range(0, 6):
self.tabella_articoli.setItem(tablerow, rigavalore, QtWidgets.QTableWidgetItem(str(row[rigavalore])))
rigavalore+= 1
tablerow+= 1
def insert(self):
rows = self.tabella_articoli.rowCount()
tablerow = 0
for row in range (0, rows):
articlecode = self.tabella_articoli.item(tablerow, 1).text()
articledesc = self.tabella_articoli.item(tablerow, 2).text()
netweight = float(self.tabella_articoli.item(tablerow, 3).text())
grossweight = float(self.tabella_articoli.item(tablerow, 4).text())
price = float(self.tabella_articoli.item(tablerow, 5).text())
if self.tabella_articoli.item(tablerow, 0) == None:
IDweight = ""
else:
IDweight = int(self.tabella_articoli.item(tablerow, 0).text())
queryinsert = "INSERT INTO Pesi ( Codice_articolo, Descrizione_articolo, Peso_netto, Peso_lordo, ID_registrazione, Prezzo) VALUES (?,?,?,?,?,?)"
values = [articlecode, articledesc, netweight, grossweight, self.IDpressed[0], price]
queryupdate = "UPDATE Pesi SET Peso_lordo = ?, Prezzo = ?, Peso_netto = ? , Codice_articolo = ?, Descrizione_articolo = ? WHERE ID = ? "
valuesupdate = [grossweight, price, netweight, articlecode, articledesc, IDweight]
exist = str(c.execute("IF EXISTS (SELECT * FROM CARICO_VIAGGI..Pesi WHERE ID = ?) BEGIN SELECT 1 END ELSE BEGIN SELECT 2 END", (IDweight)).fetchone()[0])
if exist == "1":
c.execute(queryupdate, valuesupdate)
c.commit()
print(type(IDweight))
elif exist == "2":
c.execute(queryinsert, values)
c.commit()
else:
print("Impossibile salvare gli articoli, riprovare")
tablerow+= 1
self.tabella_articoli.clearContents()
tablerow = 0
self.conteggiox = int(str(c.execute("SELECT COUNT(ID_registrazione) FROM Pesi WHERE ID_registrazione = ? ", self.IDpressed[0]).fetchone()[0]))
for row in c.execute("SELECT * FROM Pesi WHERE ID_registrazione = ? ORDER BY ID", self.IDpressed[0]):
rigavalore = 0
self.tabella_articoli.setRowCount(self.conteggiox)
for r in range(0, 6):
self.tabella_articoli.setItem(tablerow, rigavalore, QtWidgets.QTableWidgetItem(str(row[rigavalore])))
rigavalore+= 1
tablerow+= 1
app = QtWidgets.QApplication(sys.argv)
window = Ui()
app.exec_()
One solution could be to set up signals that would update the table as the user makes changes so there would be no need to refresh at all.
For example:
Set up a signal in your dialog class that will be emitted whenever the user changes the data. Then in the original dialog with the table you want to update, connect to that signal after initializing the dialog.
here is a minimal example:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def populate_table(table):
for i in range(10):
table.insertRow(table.rowCount())
for j in range(2):
item = QTableWidgetItem(type=0)
item.setText(f"({i}, {j})")
table.setItem(i,j,item)
class Dialog2(QDialog):
tableInfoChanged = pyqtSignal([int, int, str])
def __init__(self,parent=None):
super().__init__(parent=parent)
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.table = QTableWidget()
self.table.setColumnCount(2)
self.layout.addWidget(self.table)
populate_table(self.table)
self.table.cellChanged.connect(self.emitChangedInfo)
def emitChangedInfo(self, row, col):
text = self.table.item(row, col).text()
self.tableInfoChanged.emit(row, col, text)
class Dialog1(QDialog):
def __init__(self,parent=None):
super().__init__(parent=parent)
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.table = QTableWidget()
self.table.setColumnCount(2)
self.button = QPushButton("Push to open dialog2")
self.layout.addWidget(self.table)
self.layout.addWidget(self.button)
populate_table(self.table)
self.button.clicked.connect(self.openDialog2)
def updateTable(self, row, col, text):
self.table.item(row,col).setText(text)
def openDialog2(self):
self.dialog2 = Dialog2()
self.dialog2.tableInfoChanged.connect(self.updateTable)
self.dialog2.exec()
app = QApplication(sys.argv)
window = Dialog1()
window.show()
sys.exit(app.exec_())
I have tested this code and should function as is.
I started today with qt compiler, so I don't have much experience in building gui. My project is about to create dynamic smart check boxes to define axes and at the end to plot several subplots to a figure.
I tried to create dynamic combo boxes that change every time I change my current selection in the combo box.
The big issue is that it crash every time i try to change a selection in the combo box.
I tried to use .clear() method but it crash every time I clicked on it.
Edit: I changed the code to make producible code. After clicking on "Load Files", you will be able the combo boxes filled. If you will change the combo box "Choose message" for example, the python crash.
The GUI
# ------------------------------------------------- -----
# ---------------------- main.py ------------------- ----
# --------------------------------------------- ---------
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.uic import loadUi
from PyQt5.QtCore import pyqtSlot
import threading , os, subprocess, importlib, platform
# Decode_class = 'MAVLinkBinFileDecoder'
# Module = importlib.import_module(Decode_class)
from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar )
import numpy as np
import random
class MatplotlibWidget(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
loadUi("gui.ui", self)
self.setWindowTitle ( "PyQt5 & Matplotlib Example GUI" )
self.loadfiles = 0
self.first_run = 0
self.progressBar.setProperty("value", 0)
# self.pushButton_load_files.setEnabled(False)
self.pushButton_add_to_graph.setEnabled(False)
self.pushButton_choose_xml_file.clicked.connect(self.open_xml_FileNamesDialog)
self.pushButton_choose_bin_files.clicked.connect(self.open_bin_FileNamesDialog)
self.pushButton_load_files.clicked.connect(self.load_files)
self.comboBox_choose_file.currentIndexChanged.connect(self.selectionchange_file)
self.comboBox_message.currentIndexChanged.connect(self.selectionchange_message)
self.comboBox_system_id.currentIndexChanged.connect(self.selectionchange_system_id)
self.pushButton_save_plot.clicked.connect(self.update_graph)
self.file_to_graph_demo = [({'HEARTBEAT':[{'type':[12],'autopilot':[0]},{'type':[2,2,0],'autopilot':[0,0,0]}], 'CHAMBER_STATUS':[{'time_boot_ms':[1,1,1], 'chamber_num':[1,2,3]}], 'ATTITUDE':[{'test':[0,0,0,],'check':[1,1,1]}, {'test':[0,0,0,],'check':[1,1,1]}, 0 , 0, {'test':[0,0,0,],'check':[1,1,1]}]},'test')]
self.addToolBar(NavigationToolbar(self .MplWidget.canvas, self))
#pyqtSlot()
def open_xml_FileNamesDialog(self):
self.loadfiles += 1
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
self.filename, _ = QFileDialog.getOpenFileNames(self, "QFileDialog.getOpenFileNames()", "",
"Xml Files (*.xml)", options=options)
if self.loadfiles == 2:
self.pushButton_load_files.setEnabled(True)
self.pushButton_choose_xml_file.setVisible(False)
#pyqtSlot()
def open_bin_FileNamesDialog(self):
self.loadfiles += 1
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
self.list_of_file_paths, _ = QFileDialog.getOpenFileNames(self, "QFileDialog.getOpenFileNames()", "",
"Bin Files (*.bin)", options=options)
if self.loadfiles == 2:
self.pushButton_load_files.setEnabled(True)
self.pushButton_choose_bin_files.setVisible(False)
#pyqtSlot()
def load_files(self):
# parse = Module.Logic_bin_to_mat_parser(self.filename[0])
# parse.generate_dialect_from_xml() # Run Mavgenerate xml function
# value = 19
# self.progressBar.setProperty("value", value)
# self.file_to_graph = []
# for path in self.list_of_file_paths: # Parse and create Matlab from each bin file
# parse.decode_messages(path)
# parse.create_dictionary_of_amount_of_messages_by_type()
# parse.parse_bin_to_mat()
# self.file_to_graph.append((parse.save, parse.file_base_name))
# parse.convert_parse_dictionary_to_mat()
# value += (100 - 20) / len(self.list_of_file_paths)
# self.progressBar.setProperty("value", value)
# value = 100
# self.progressBar.setProperty("value", value)
# self.pushButton_load_files.setVisible(False)
# self.progressBar.setVisible(False)
for option in self.file_to_graph_demo:
self.comboBox_choose_file.addItem(option[1])
#pyqtSlot()
def selectionchange_file(self):
self.first_run += 1
combobox_enty = self.comboBox_choose_file.currentText()
self.file_idx = self.comboBox_choose_file.findText(combobox_enty)
list_of_messages = []
for message in self.file_to_graph_demo[self.file_idx][0].items():
list_of_messages.append(message[0])
if self.first_run >= 1:
self.comboBox_message.clear()
self.comboBox_message.addItems(list_of_messages)
#pyqtSlot()
def selectionchange_message(self):
self.first_run += 1
self.combobox_entry_message = self.comboBox_message.currentText()
self.message_idx = self.comboBox_message.findText(self.combobox_entry_message)
list_of_system_ids = []
count = 0
for idx, system_id in enumerate(self.file_to_graph_demo[self.file_idx][0][self.combobox_entry_message]):
if system_id != 0:
count += 1
list_of_system_ids.append(str(idx+1))
if self.first_run >= 2:
self.comboBox_system_id.clear()
self.comboBox_system_id.addItems(list_of_system_ids)
#pyqtSlot()
def selectionchange_system_id(self):
self.combobox_entry_system_id = int(self.comboBox_system_id.currentText())-1
self.system_id_idx = self.comboBox_system_id.findText(str(self.combobox_entry_system_id))
for field in self.file_to_graph_demo[self.file_idx][0][self.combobox_entry_message][self.system_id_idx]:
self.comboBox_y_axis.addItem(field)
self.comboBox_x_axis.addItem(field)
def update_graph(self):
fs = 500
f = random.randint(1, 100)
ts = 1 / fs
length_of_signal = 100
t = np . linspace (0, 1, length_of_signal )
cosinus_signal = np . cos ( 2 * np . pi * f * t )
sinus_signal = np . sin ( 2 * np . pi * f * t )
self.MplWidget.canvas.axes.clear()
self.MplWidget.canvas.axes.plot(t,cosinus_signal)
self.MplWidget.canvas.axes.plot(t,sinus_signal)
self.MplWidget.canvas.axes.legend(('cosinus', 'sinus'), loc='upper right')
self.MplWidget.canvas.axes.set_title(' Cosinus - Sinus Signal')
self.MplWidget.canvas.draw()
if __name__ == '__main__':
app=QApplication([])
app.setStyle('Fusion')
window=MatplotlibWidget()
window.show()
app.exec_()
Your issue seems to be in MatplotlibWidget.selectionchange_system_id(). You are trying to cast the current text of self.comboBox_system_id to an int, but this will cause an exception when the current text can't be converted. This is the case just after self.comboBox_system_id is cleared because at that point the current text of the combi box is an empty string. The easiest way to get around this is to test if the current text can be cast to an integer first before continuing, i.e.
def selectionchange_system_id(self):
if self.comboBox_system_id.currentText().isdigit():
self.combobox_entry_system_id = int(self.comboBox_system_id.currentText())-1
...
I have a Excel as Below
|---------------------|------------------|
| Heading 1 | Heading 2 |
|---------------------|------------------|
| Row1 | Value 1 |
|---------------------|------------------|
| Row2 | Value 2 |
|---------------------|------------------|
I am reading from excel and Showing the Values of Heading 1 in the GUI
When I click on submit Button , I need to read the value/text of the CheckBox depending on the selection of the CheckBox and Create XML by using Excel for only selected values
Problem is How can I only select the values in the Excel , depending on the selection of check Box. (But I know how to identify which check box is checked ). But how to relate to Excel is I am facing problem
Note: I Know how to create XML from excel
I know how to identify when submit is clicked
GUI Code:
Config.Py
import tkinter as tk
import xlrd
import GetValueFromExcel
from GetValueFromExcel import ExcelValue
from array import array
from tkinter import *
from tkinter import ttk, Button
from tkinter import *
root = Tk()
class UICreation():
def __init__(self):
print ("I m in __init__")
self.tabControl = ttk.Notebook(root)
self.tab1 = ttk.Frame(self.tabControl)
self.tab2 = ttk.Frame(self.tabControl)
def tabcreation(self):
print ("I M in Tab Creation")
self.tabControl.add(self.tab1 , text="Tab1")
#self.tabControl(self.tab1, text= t)
##self.tabControl(self.tab1, )
self.tabControl.add(self.tab2, text="Tab2")
self.tabControl.grid()
def checkbox(self):
print ("I M in checkBox")
checkBox1 = Checkbutton(self.tab1, text=str(t[0]))
checkBox2 = Checkbutton(self.tab1, text=str(t[1]))
Checkbutton()
checkBox1.grid()
checkBox2.grid()
def button(self):
button = Button(self.tab1 , text="Submit", command=self.OnButtonClick)
button.grid()
def OnButtonClick(self):
print ("I am Working")
if __name__ == '__main__':
ui = UICreation()
ev = GetValueFromExcel.ExcelValue()
ev.readExcelValue()
t = ev.readExcelValue()
print(t)
ui.tabcreation()
ui.checkbox()
ui.button()
#ev = readExcelValue()
root.mainloop()
GetValueFromExcel.py
import xlrd
class ExcelValue():
def __init__(self):
self.wb=xlrd.open_workbook(r"C:\<FilePath>\Filename.xlsx")
#self.ws=self.wb.sheet_by_name("Sheet1")
for sheet in self.wb.sheets():
self.number_of_rows = sheet.nrows
self.number_of_columns = sheet.ncols
def readExcelValue(self):
result_data = []
row_data = []
for sheet in self.wb.sheets():
for curr_row in range(1, self.number_of_rows, 1):
#for curr_col in range(0, self.number_of_columns , 1):
#data = sheet.cell_value(curr_row, curr_col) # Read the data in the current cell
data = sheet.cell_value(curr_row, 0)
#print(data)
row_data.append(data)
result_data.append(row_data)
return result_data[1]
You can pass the value to Checkbutton like this:
def checkbox(self):
print ("I M in checkBox")
checkBox1 = Checkbutton(self.tab1, text=str(t.keys()[0]), variable=t.values()[0])
checkBox2 = Checkbutton(self.tab1, text=str(t.keys()[1]), variable=t.values()[1])
Checkbutton()
checkBox1.grid()
checkBox2.grid()
and you must change readExcelValue, like below:
def readExcelValue(self):
result_data = {}
for sheet in self.wb.sheets():
for curr_row in range(1, self.number_of_rows, 1):
data = sheet.cell_value(curr_row, 0)
value = sheet.cell_value(curr_row, 1)
result_data[data] = value
return result_data
I am using code in wxPython to show images.
I created a screen with 2 panels, one left and right.
In one of the panels (randomly chosen), I want do display an image for exactly 150ms.
How can I program this? I am relatively new to Python, and I don't find any clear way on the internet.
My code for now (without the 150ms):
import wxversion
wxversion.select("3.0")
import wx
import random
import timeclass Screen_1(wx.Dialog):
ri = 0
def __init__(self,parent,id,title):
wx.Dialog.__init__(self,parent,id,title,size=(400,300))
self.randomImage = random.randrange(1,3)
self.randomSlot = random.randrange(1,3)
Screen_1.ri = self.randomImage
if(self.randomSlot == 1):
self.side = 'Left'
else:
self.side = 'Right'
file = open('User.txt','a')
panel_left = wx.Panel(self,11,(-1,-1),(200,200))
self.picture_left = wx.StaticBitmap(panel_left)
font = wx.Font(13,wx.DEFAULT,wx.NORMAL,wx.BOLD)
panel_centre = wx.Panel(self,12,(200,70),(10,100))
msg = wx.StaticText(panel_centre,-1,'+',size=(10,100))
msg.SetFont(font)
panel_right = wx.Panel(self,13,(210,0),(200,200))
self.picture_right = wx.StaticBitmap(panel_right)
**self.imageName = 'im_'+str(self.randomImage)+'.png'**
if self.randomSlot == 1:
self.picture_left.SetBitmap(wx.Bitmap(self.imageName))
else:
self.picture_right.SetBitmap(wx.Bitmap(self.imageName))
wx.FutureCall(1000,self.Destroy)
self.Centre()
self.ShowModal()
def OnClick(self,event):
self.Close()
Thanks a lot!
def OnTimeUp(self,e):
#change images
self.timer.Start(15,oneShot=True) # if you want to call it again in 15 ms
def StartTimer(self):
self.timer = wx.Timer()
self.timer.Bind(wx.EVT_TIMER,self.OnTimeUp)
self.timer.Start(15,oneShot=True)
something like that ... although 15ms is very fast ...
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