How make items in combobox appear in one selection instead of selecting them only one by one? - pyqt4

How do you get items that are added to qcomboBox with click of push button to appear as example: '10, 23, 56, 14, 57, ... ' instead of only having them all appear in the drop down menu and only selecting them one by one? Here is my code:
def setup(self, Dialog):
...
self.comboBox = QtGui.QComboBox(Dialog)
self.comboBox.setGeometry(QtCore.QRect(20, 100, 431, 22))
self.comboBox.setObjectName(_fromUtf8("comboBox"))
self.tableWidget = QtGui.QTableWidget(Dialog)
self.tableWidget.setGeometry(QtCore.QRect(20, 470, 651, 71))
self.tableWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.tableWidget.setTextElideMode(QtCore.Qt.ElideRight)
self.tableWidget.setVerticalScrollMode(QtGui.QAbstractItemView.ScrollPerItem)
self.tableWidget.setRowCount(1)
self.tableWidget.setColumnCount(129)
self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
item = QtGui.QTableWidgetItem()
for i in range(0, self.tableWidget.columnCount()):
self.tableWidget.setItem(0, i, item)
self.pushButton_7 = QtGui.QPushButton(Dialog)
self.pushButton_7.setGeometry(QtCore.QRect(220, 650, 75, 23))
self.pushButton_7.setObjectName(_fromUtf8("pushButton_7"))
self.pushButton_7.clicked.connect(self.additem)
def additem(self):
for i in range(0, self.tableWidget.columnCount()):
item = self.tableWidget.item(0,i)
if item != None:
text = item.text()
self.comboBox.addItem(text)

your additem method should look like this:
def additem(self):
text = ""
for i in range(0, self.tableWidget.columnCount()):
item = self.tableWidget.item(0,i)
if item != None:
text += item.text() + ", "
self.comboBox.addItem(text[:-2])

Related

How to link two classes in python for eg a student class and a subject class such that a student class contains a number objects of subject class

class Subject:
def __init__(self, name, midTerm, attend, classtest, endterm):
self.name = name
self.midTerm = midTerm
self.attend = attend
self.classtest = classtest
self.endterm = endterm
self.total = 0
self.grade = 'F'
newAttend = attendanceMarks(self.attend)
if newAttend != -1:
self.total = newAttend + midTermMarks(midTerm) + classTestMarks(classtest) + endTermMarks(endterm)
self.grade = gradeCal(self.total)
else:
self.grade = 'F'
class Student:
sub = []
def __init__(self, name, roll, s1, s2, s3, s4):
self.name = name
self.roll = roll
self.sub.append(s1)
self.sub.append(s2)
self.sub.append(s3)
self.sub.append(s4)
self.tTotal = self.sub[0].total + self.sub[1].total + self.sub[2].total + self.sub[3].total
self.tGrade = gradeCal(self.tTotal / 4)
st1 = Student("Akash", 17, Subject("Compiler Design", 50, 76, 50, 100), Subject("Software Engineering", 50, 76, 50, 100), Subject("Machine Learning", 50, 76, 50, 100), Subject("Natural Language Processing", 50, 76, 50, 100))
st2 = Student("Juan", 23, Subject("Compiler Design", 30, 76, 25, 50), Subject("Software Engineering", 25, 76, 34, 60), Subject("Machine Learning", 39, 76, 45, 66), Subject("Natural Language Processing", 32, 76, 44, 77))
st1.tTotal
st2.tTotal
Here both st1.tTotal and st2.tTotal gives the same output. Some of the methods used above are already defined and the code executes successfully. The total and grade inside subject class are calculated in terms of 100 marks and grades A-F respectively.
The reason why st1.tTotal and st2.tTotal give the same output is that you're defining Student.sub as a class variable so it is shared across all Student instances. You should instead make Student.sub an instance attribute by defining it in the __init__ method and bind it to self so that each Student object has its own sub list.
Change:
class Student:
sub = []
def __init__(self, name, roll, s1, s2, s3, s4):
self.name = name
self.roll = roll
self.sub.append(s1)
self.sub.append(s2)
self.sub.append(s3)
self.sub.append(s4)
to:
class Student:
def __init__(self, name, roll, s1, s2, s3, s4):
self.name = name
self.roll = roll
self.sub = []
self.sub.append(s1)
self.sub.append(s2)
self.sub.append(s3)
self.sub.append(s4)
or to allow a variable number of subjects for each Student, use a variable argument with an asterisk:
class Student:
def __init__(self, name, roll, *sub):
self.name = name
self.roll = roll
self.sub = sub

Getting a list variable out of Tkinter window

I am trying to get a list out of Tkinter and I want to add a Y-axis scroll bar to the list box but don't know-how. My code is as follows:
window = Tk()
window.title('Select Multiple Industries')
window.geometry('400x800')
def showindowelected():
industries = []
iname = lb.curselection()
for i in iname:
op = lb.get(i)
industries.append(op)
print (industries)
window.destroy()
#for val in industries:
#print(val)
show = Label(window, text = "Select Multiple Industries", font = ("Times", 14), padx = 10, pady = 10)
show.pack()
lb = Listbox(window, selectmode = "multiple")
lb.pack(padx = 10, pady = 10, expand = YES, fill = "both")
x = ["Brewing","Papermills","Cheese Manufacturing","Steel Mill", "Salt Making"]
for item in range(len(x)):
lb.insert(END, x[item])
lb.itemconfig(item, bg = "whitesmoke" if item % 2 == 0 else "silver")
Button(window, text=" Select > ", command=showindowelected, bg='green', fg='white').pack()
window.mainloop()
Once the window is destroyed, I want the selected variables stored in a list.

local variable referenced before assignment - Surely not this difficult

I'm trying to write a script to control movements of a camera. I'm writing it in Thonny on a Raspberry Pi. I receive the following error when trying to move the camera using the GUI buttons. I've asked around and tried troubleshooting the problem but no luck yet.
if anyone can help that'd be awesome.
I appreciate there are alternative workflows to this script but it's me combining an old script with a new GUI so I'd love to see if they could be merged. If not oh well, I'll implement the other workflow.
[Here is the error message from Thonny][1]
from tkinter import *
import RPi.GPIO as GPIO
import time
import datetime, sys, tty, termios
#defining root
root = Tk()
root.title('Operation Little Brother V02')
#setting GPIO board
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3,GPIO.OUT)
servo1 = GPIO.PWM(3, 50)
GPIO.setup(5,GPIO.OUT)
servo2 = GPIO.PWM(5, 50)
#setting servos to off
servo1.start(0)
servo2.start(0)
#user input section
dummy = input('Initiate project. Press Enter')
#setting servos to 90degrees/startup sequence
print('launching start up sequence')
servo1.ChangeDutyCycle(6)
time.sleep(1)
servo1.ChangeDutyCycle(0)
time.sleep(1)
print ('servo 1 test complete')
servo2.ChangeDutyCycle(6)
time.sleep(1)
servo2.ChangeDutyCycle(0)
print ('servo 2 test complete')
# Defining Functions
#x axis movement concept
def x_movement(x_dir):
if x_axis <= limit_x_left and x_axis >= limit_x_right:
x_axis = x_axis + x_dir
servo1.ChangeDutyCycle(x_axis)
time.sleep(0.3)
servo1.ChangeDutyCycle(0)
time.sleep(0.5)
print ('moved camera to position: ' +str(x_axis) + '/' +str(limit_x_left))
return
else:
print ('limits reached')
#y axis movement concept
def y_movement(y_dir):
if y_axis <= limit_y_down and y_axis >= limit_y_up:
y_axis = y_axis + y_dir
servo2.ChangeDutyCycle(y_axis)
time.sleep(0.3)
servo2.ChangeDutyCycle(0)
time.sleep(0.5)
print('moved camera to position: ' +str(y_axis) + '/' +str(limit_y_up))
return y_axis
else:
print ('limits reached')
#centre movement
def centre_movement():
y_axis = 6
servo2.ChangeDutyCycle(6)
servo2.ChangeDutyCycle(0)
time.sleep(0.5)
x_axis = 6
servo1.ChangeDutyCycle(6)
servo1.ChangeDutyCycle(0)
time.sleep(0.5)
print('camera centered to position 6')
return
#off sequence
def off():
servo1.ChangeDutyCycle(0)
servo2.ChangeDutyCycle(0)
servo1.stop()
servo2.stop()
GPIO.cleanup()
print('Whoopty fucking doo it\'s finished')
exit()
#defining limits for x and y axis
limit_x_left = 9
limit_x_right = 3
limit_y_up = 3
limit_y_down = 9
x_axis = 6
y_axis = 6
#frame creation
frame1 = LabelFrame(root, text = 'Welcome to Operation Little Brother', padx = 25, pady = 25, border = 5, fg = '#ffffff', bg = '#3e556b')
#button creation
button1_left = Button(frame1, text = 'Left', padx = 20, pady = 20, fg = 'purple', bg = '#63778a', command = lambda: x_movement(1))
button2_right = Button(frame1, text = 'Right', padx = 20, pady = 20, fg = 'orange', bg = '#63778a', command = lambda: x_movement(-1))
button3_up = Button(frame1, text = 'Up', padx = 20, pady = 20, fg = 'green', command = lambda: y_movement(1))
button4_down = Button(frame1, text = 'Down', padx = 20, pady = 20, fg = 'blue', command = lambda: y_movement(-1))
button5_centre = Button(frame1, text = 'Centre', padx = 20, pady = 20, fg = 'black', command = lambda: centre_movement())
button6_start = Button(frame1, text = 'Start', padx = 10, pady = 10, fg = 'green')
button7_stop = Button(frame1, text = 'Stop', padx = 10, pady = 10, fg = 'red', command = lambda: off())
#positioning the frame
frame1.pack()
#button positioning
button1_left.grid(row = 3, column = 0,)
button2_right.grid(row = 3, column = 2,)
button3_up.grid(row = 2, column = 1)
button4_down.grid(row = 4, column = 1)
button5_centre.grid(row = 3, column = 1)
button6_start.grid(row = 1, column = 0)
button7_stop.grid(row = 1, column = 2)
#Text formatting
button1_left.configure(font='Calibri 15')
button2_right.configure(font='Calibri 15')
button3_up.configure(font='Calibri 15')
button4_down.configure(font='Calibri 15')
button5_centre.configure(font='Calibri 15')
button6_start.configure(font='Calibri 15')
button7_stop.configure(font='Calibri 15')
# Window Loop
root.mainloop()
[1]: https://i.stack.imgur.com/xIc0O.png

MousePressEvent inside my Pyqt PlotWidget- Simulate event

This is full code base. Im trying to simulate a mouse click in the graph which is self.graph which is a plotwidget. I want the mouse click to happen in the plotrunnable class so afte I click the graph button it will automatically update and right before going to sleep it will simulate a click on the graph to make it seem like its automatically updating
# Form implementation generated from reading ui file 'U:\Embedded Graphics View2.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import pyqtgraph as pg
import pyodbc as db
import pandas as pd
import time, os
from time import strptime as strptime
from time import mktime as mktime
from time import gmtime, strftime
from pyqtgraph import AxisItem
from datetime import datetime, timedelta
from numpy import ceil
import numpy as np
import sip
os.environ['TZ']='EST'
now=time.asctime(time.localtime())
start_time=time.time()
print('starting at '+now)
def time(date):
if date == '':
return None
else:
datetime = date
pattern = '%Y%m%d %H:%M:%S'
epoch = int(mktime(strptime(datetime, pattern)))
return epoch
def connecttosql():
host='{SQL Server}'
server='SERVER' ######### DEV - WILL CHANGE TO PRODUCTION WHEN DELIVERED
database='DB'
username='user'
password='pass'
try:
cs= 'Driver=%s;Server=%s;Uid=%s;Pwd=%s;Database=%s;' % (host,server, username, password, database)
global conn #### THIS WILL BE USED ON THE QUERY
conn= db.connect(cs)
print ('Connected successfully to '+host+', '+server)
except Exception as e:
print ('Error: ' + str (e))
def testconnection():
cursor=conn.cursor()
try:
cursor.execute("SELECT VERSION()")
res=cursor.fetchone()
print(res)
ver=res[0]
if ver in None:
return False
else:
return True
except:
print ("ERROR IN CONNECTION")
return False
def closeconnection():
conn.close
print('CONNECTION WITH DATABASE HAS BEEN CLOSED')
def query(ticker,interval,ST,ET):
# target='U:/py/sql csv/'+ticker+' - '+interval+'.csv'
global conn
table = 'BAR_BB' ### hard code
qry = f"SELECT * FROM {table} WHERE SY = {ticker} AND IL = {interval} AND ST >= {ST} AND ST <= {ET}"
df=pd.read_sql(qry,conn) ###### format will change
df.set_index('ST',inplace=True)
#df.to_csv(target,encoding='utf-8',index=False)
st=df.index.tolist()
op=df['O'].tolist()
hi=df['H'].tolist()
lo=df['L'].tolist()
cl=df['C'].tolist()
bars=[]
x=0
for i in st:
bar=[st[x],op[x],cl[x],lo[x],hi[x]]
bars.append(bar)
x=x+1
data=bars
return data
##Picture that goes in the UI
class CandlestickItem(pg.GraphicsObject):
def __init__(self):
pg.GraphicsObject.__init__(self)
self.flagHasData = False
#QtCore.pyqtSlot(list)
def set_data(self, data):
self.data = data
self.flagHasData = True
self.generatePicture()
self.informViewBoundsChanged()
def generatePicture(self):
## pre-computing a QPicture object allows paint() to run much more quickly,
## rather than re-drawing the shapes every time.
self.picture = QtGui.QPicture()
p = QtGui.QPainter(self.picture)
p.setPen(pg.mkPen('w'))
w = (self.data[1][0] - self.data[0][0]) / 3.
for (t, open, close, min, max) in self.data:
p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
if open > close:
p.setBrush(pg.mkBrush('r'))
else:
p.setBrush(pg.mkBrush('g'))
p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
p.end()
def paint(self, p, *args):
p.drawPicture(0, 0, self.picture)
def boundingRect(self):
## boundingRect _must_ indicate the entire area that will be drawn on
## or else we will get artifacts and possibly crashing.
## (in this case, QPicture does all the work of computing the bouning rect for us)
return QtCore.QRectF(self.picture.boundingRect())
class DateAxisItem(AxisItem):
"""
A tool that provides a date-time aware axis. It is implemented as an
AxisItem that interpretes positions as unix timestamps (i.e. seconds
since 1970).
The labels and the tick positions are dynamically adjusted depending
on the range.
It provides a :meth:`attachToPlotItem` method to add it to a given
PlotItem
"""
# Max width in pixels reserved for each label in axis
_pxLabelWidth = 80
def __init__(self, *args, **kwargs):
AxisItem.__init__(self, *args, **kwargs)
self._oldAxis = None
def tickValues(self, minVal, maxVal, size):
"""
Reimplemented from PlotItem to adjust to the range and to force
the ticks at "round" positions in the context of time units instead of
rounding in a decimal base
"""
maxMajSteps = int(size/self._pxLabelWidth)
dt1 = datetime.fromtimestamp(minVal)
dt2 = datetime.fromtimestamp(maxVal)
dx = maxVal - minVal
majticks = []
if dx > 63072001: # 3600s*24*(365+366) = 2 years (count leap year)
d = timedelta(days=366)
for y in range(dt1.year + 1, dt2.year):
dt = datetime(year=y, month=1, day=1)
majticks.append(mktime(dt.timetuple()))
elif dx > 5270400: # 3600s*24*61 = 61 days
d = timedelta(days=31)
dt = dt1.replace(day=1, hour=0, minute=0,
second=0, microsecond=0) + d
while dt < dt2:
# make sure that we are on day 1 (even if always sum 31 days)
dt = dt.replace(day=1)
majticks.append(mktime(dt.timetuple()))
dt += d
elif dx > 172800: # 3600s24*2 = 2 days
d = timedelta(days=1)
dt = dt1.replace(hour=0, minute=0, second=0, microsecond=0) + d
while dt < dt2:
majticks.append(mktime(dt.timetuple()))
dt += d
elif dx > 7200: # 3600s*2 = 2hours
d = timedelta(hours=1)
dt = dt1.replace(minute=0, second=0, microsecond=0) + d
while dt < dt2:
majticks.append(mktime(dt.timetuple()))
dt += d
elif dx > 1200: # 60s*20 = 20 minutes
d = timedelta(minutes=10)
dt = dt1.replace(minute=(dt1.minute // 10) * 10,
second=0, microsecond=0) + d
while dt < dt2:
majticks.append(mktime(dt.timetuple()))
dt += d
elif dx > 120: # 60s*2 = 2 minutes
d = timedelta(minutes=1)
dt = dt1.replace(second=0, microsecond=0) + d
while dt < dt2:
majticks.append(mktime(dt.timetuple()))
dt += d
elif dx > 20: # 20s
d = timedelta(seconds=10)
dt = dt1.replace(second=(dt1.second // 10) * 10, microsecond=0) + d
while dt < dt2:
majticks.append(mktime(dt.timetuple()))
dt += d
elif dx > 2: # 2s
d = timedelta(seconds=1)
majticks = range(int(minVal), int(maxVal))
else: # <2s , use standard implementation from parent
return AxisItem.tickValues(self, minVal, maxVal, size)
L = len(majticks)
if L > maxMajSteps:
majticks = majticks[::int(ceil(float(L) / maxMajSteps))]
return [(d.total_seconds(), majticks)]
def tickStrings(self, values, scale, spacing):
"""Reimplemented from PlotItem to adjust to the range"""
ret = []
if not values:
return []
if spacing >= 31622400: # 366 days
fmt = "%Y"
elif spacing >= 2678400: # 31 days
fmt = "%Y %b"
elif spacing >= 86400: # = 1 day
fmt = "%b/%d"
elif spacing >= 3600: # 1 h
fmt = "%b/%d-%Hh"
elif spacing >= 60: # 1 m
fmt = "%H:%M"
elif spacing >= 1: # 1s
fmt = "%H:%M:%S"
else:
# less than 2s (show microseconds)
# fmt = '%S.%f"'
fmt = '[+%fms]' # explicitly relative to last second
for x in values:
try:
t = datetime.fromtimestamp(x)
ret.append(t.strftime(fmt))
except ValueError: # Windows can't handle dates before 1970
ret.append('')
return ret
def attachToPlotItem(self, plotItem):
"""Add this axis to the given PlotItem
:param plotItem: (PlotItem)
"""
self.setParentItem(plotItem)
viewBox = plotItem.getViewBox()
self.linkToView(viewBox)
self._oldAxis = plotItem.axes[self.orientation]['item']
self._oldAxis.hide()
plotItem.axes[self.orientation]['item'] = self
pos = plotItem.axes[self.orientation]['pos']
plotItem.layout.addItem(self, *pos)
self.setZValue(-1000)
def detachFromPlotItem(self):
"""Remove this axis from its attached PlotItem
(not yet implemented)
"""
raise NotImplementedError() # TODO
class TimeAxisItem(pg.AxisItem):
def tickStrings(self, values, scale, spacing):
return [datetime.fromtimestamp(value) for value in values]
##UI SetUP
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1442, 1018)
MainWindow.setAutoFillBackground(False)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.graphicsView = QtWidgets.QWidget(self.centralwidget)
self.flagHasData = False
self.graphicsView.setGeometry(QtCore.QRect(0, 0, 1201, 991))
font = QtGui.QFont()
font.setPointSize(18)
self.graphicsView.setFont(font)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
self.graphicsView.setObjectName("graphicsView")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setEnabled(True)
self.lineEdit.setGeometry(QtCore.QRect(1280, 20, 151, 21))
font = QtGui.QFont()
font.setPointSize(11)
self.lineEdit.setFont(font)
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(1280, 80, 151, 20))
font = QtGui.QFont()
font.setPointSize(11)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setText("")
self.lineEdit_2.setObjectName("lineEdit_2")
self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_3.setGeometry(QtCore.QRect(1280, 160, 151, 20))
font = QtGui.QFont()
font.setPointSize(11)
self.lineEdit_3.setFont(font)
self.lineEdit_3.setObjectName("lineEdit_3")
self.lineEdit_4 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_4.setGeometry(QtCore.QRect(1280, 230, 151, 20))
font = QtGui.QFont()
font.setPointSize(11)
self.lineEdit_4.setFont(font)
self.lineEdit_4.setObjectName("lineEdit_4")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(1280, 0, 91, 16))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(1280, 60, 111, 16))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(1280, 120, 51, 16))
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(1280, 190, 101, 16))
self.label_4.setObjectName("label_4")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(1280, 260, 75, 23))
self.pushButton.setObjectName("pushButton")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(1280, 140, 170, 20))
self.label_5.setObjectName("label_5")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(1280, 210, 170, 20))
self.label_6.setObjectName("label_6")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(1360, 260, 75, 23))
self.pushButton_2.setObjectName("pushButton_2")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.pushButton.clicked.connect(self.btn_click)
self.pushButton_2.clicked.connect(self.clear)
self.main_layout = QtWidgets.QHBoxLayout()
self.graphicsView.setLayout(self.main_layout)
self.graph = None
self.glayout = None
self.data = []
self.vb = None
self.main_layout.addWidget(self.graph)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
##renaming all the Labels and Window
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Graph Interface"))
self.label.setText(_translate("MainWindow", "Ticker (Bloomberg)"))
self.label_2.setText(_translate("MainWindow", "Interval (In Seconds)"))
self.label_3.setText(_translate("MainWindow", "Start Time"))
self.label_4.setText(_translate("MainWindow", "End Time (Optional)"))
self.pushButton.setText(_translate("MainWindow", "Graph"))
self.label_5.setText(_translate("MainWindow", "YYYYMMDD 00:00:00 (UTC)"))
self.label_6.setText(_translate("MainWindow", "YYYYMMDD 00:00:00 (UTC)"))
self.pushButton_2.setText(_translate("MainWindow", "Clear"))
global mouse_click_event
def mouse_click_event(self):
graph.clicked()
#Button Click function.
def btn_click(self):
global ticker, interval, start_time, end_time, graph
global DRAW_GRAPH
connecttosql()
self.data = [ ## fields are (time, open, close, min, max).
(1., 10, 13, 5, 15),
(2., 13, 17, 9, 20),
(3., 17, 14, 11, 23),
(4., 14, 15, 5, 19),
(5., 15, 9, 8, 22),
(6., 9, 15, 8, 16)]
self.graph = pg.PlotWidget(name = 'Whatever', aixsItems = {'bottom' : TimeAxisItem(orientation = 'bottom')})
# self.ticker = self.lineEdit.text()
#self.interval = self.lineEdit_2.text()
#self.start_time = time(self.lineEdit_3.text())
#self.end_time = time(self.lineEdit_4.text())
# if self.end_time == None:
# self.end_time = time(strftime("%Y%m%d %H:%M:%S", gmtime()))
# else:
# self.end_time = time((self.lineEdit_4.text()))
# self.ticker = "'{}'".format(self.ticker)
# self.interval = "'{}'".format(self.interval)
# ticker = self.ticker
# interval = self.interval
# start_time = self.start_time
# end_time = self.end_time
self.glayout = pg.GraphicsLayout()
self.vb = self.glayout.addViewBox()
self.vb.enableAutoRange(axis='xy',enable = True)
#self.data = query(self.ticker,self.interval,self.start_time,self.end_time)
self.item = CandlestickItem()
self.item.set_data(self.data)
self.graph.addItem(self.item)
self.axis1 = DateAxisItem(orientation = 'bottom')
self.axis1.attachToPlotItem(self.graph.getPlotItem())
self.graph.showGrid(y=True, alpha = 0.8)
self.main_layout.addWidget(self.graph)
runnable = PlotRunnable(self.item)
QtCore.QThreadPool.globalInstance().start(runnable)
def clear(self):
self.parent = self.graph.parent()
self.graph.setParent(None)
self.graph.setParent(self.parent)
class PlotRunnable(QtCore.QRunnable):
def __init__(self, it):
QtCore.QRunnable.__init__(self)
self.it = it
def run(self):
while True:
data = self.it.data
# end_time = end_time = time(strftime("%Y%m%d %H:%M:%S", gmtime()))
rand =[ ## fields are (time, open, close, min, max).
(1., 10, 13, 5, 15),
(2., 13, 17, 9, 20),
(3., 17, 14, 11, 23),
(4., 14, 15, 5, 19),
(5., 15, 9, 8, 22),
(6., 9, 15, 8, 16),
(7., 8, 16, 10, 17)]
new_bar = rand[-1]
data.append(new_bar)
QtCore.QMetaObject.invokeMethod(self.it, "set_data",
QtCore.Qt.QueuedConnection,
QtCore.Q_ARG(list, data))
#put mouse click here
print("ran")
#interval = int("{}".format(interval))
QtCore.QThread.msleep(1000)
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()

Insertion of data into a treeview widget on a notebook Tab

I have included two modules:
A treeview Module
A notebook Module
The treeview module seems to function as required and gets its data from sample data at the top of the Module
The notebook module creates a notebook with 12 tabs - one for each month of the year. each tab will have a treeview widget on it showing the data for that month.
Question # 1:
How do I enter the treeview widget and its data from the treeview module on each tab of the notebook? No Mater what I try I end up with a blank treeview widget as demonstrated in the current module
Question # 2:
Column #3 of the treeview module has both negative and positive numbers in it. How do I make the positive numbers "green" and the Negative numbers "red" while keeping the rest of the widget in its default "black".?
(every time I try to use 'tag' and 'tag-configure' it changes all the characters on the widget.)
'''the following is a tree module
in order to run this module remove "#" from the last line'''
from tkinter import *
import tkinter.ttk as ttk
CategoryList = ['Income','Taxes','Housing']
AccountsList = [['Income','Bobs'],['Income','Roses'],['Income','Als'],
['Taxes','Federal'],['Taxes','State'],['Taxes','Local'],
['Housing','Payment'],['Housing','Utilities'], ['Housing','Repairs']]
CatDiffList = [[5000,4500,500],[100,120,-20],[800,700,100]]
AcctDiffList = [[2000,2000,0],[2000,2000,0],[1000,500,500],
[70,50,20],[50,50,0],[0,40,-40],
[500,400,0],[200,100,100],[100,0,100]]
month = 3 #numbers 1 to 12 = the twelve months
def CreateTreeview():
root = Tk()
#Set up the tree
tree = ttk.Treeview(root,height = 20 )
tree["columns"]=("one","two","three")
tree.column("one", width=100,anchor = 'e' )
tree.column("two", width=100,anchor = 'e')
tree.column("three", width=100,anchor = 'e')
tree.heading('#0',text = "Account Names")
tree.heading("one", text="Budget")
tree.heading("two", text="Actual")
tree.heading("three", text="Difference")
#Bring in Data from TransactionTotals Module & insert it in the tree
for r in range(0,len(CategoryList)):
Name = CategoryList[r]
CatBud = CatDiffList[r][0]
CatAct = CatDiffList[r][1]
CatDif = CatDiffList[r][2]
if CatDif >= 0:
fg = "green" #Change color of column 3
else:
fg = "red"
tree.tag_configure("col3", foreground = fg)
tree.insert("" , r,Name, text=Name, values=(CatBud,CatAct,CatDif),
tag =("col3"))
AcctBud = AcctDiffList[r][0]
AcctAct = AcctDiffList[r][1]
AcctDif = AcctDiffList[r][2]
if AccttDif >= 0:
fg = "green" #Change color of column 3
else:
fg = "red"
tree.tag_configure("col3", foreground = fg)
for y in range(1,len(AccountsList)):
if AccountsList[y][0] == Name:
tree.insert(Name,2,text = AccountsList[y][1],
values = (AcctBud,AcctAct,AcctDif),
tag =("col3"))
tree.pack()
root.mainloop()
#CreateTreeview() #uncomment this line in order to test Tview.py
*******************************************************************************
'''This is the Notebook Module'''
import tkinter.ttk as ttk
import Tview as T2
from tkinter import *
class Notebook(Frame):
def __init__(self, parent, activerelief = RAISED, inactiverelief = RIDGE, xpad = 4, ypad = 6, activefg = 'black', inactivefg = 'black', **kw):
"""Construct a Notebook Widget
Notebook(self, parent, activerelief = RAISED, inactiverelief = RIDGE, xpad = 4, ypad = 6, activefg = 'black', inactivefg = 'black', **kw)
Valid resource names: background, bd, bg, borderwidth, class,
colormap, container, cursor, height, highlightbackground,
highlightcolor, highlightthickness, relief, takefocus, visual, width, activerelief,
inactiverelief, xpad, ypad.
xpad and ypad are values to be used as ipady and ipadx
with the Label widgets that make up the tabs. activefg and inactivefg define what
color the text on the tabs when they are selected, and when they are not"""
#Make various argument available to the rest of the class
self.activefg = activefg
self.inactivefg = inactivefg
self.deletedTabs = []
self.xpad = xpad
self.ypad = ypad
self.activerelief = activerelief
self.inactiverelief = inactiverelief
self.kwargs = kw
self.tabVars = {} #This dictionary holds the label and frame instances of each tab
self.tabs = 0 #Keep track of the number of tabs
self.noteBookFrame = Frame(parent) #Create a frame to hold everything together
self.BFrame = Frame(self.noteBookFrame) #Create a frame to put the "tabs" in
self.noteBook = Frame(self.noteBookFrame, relief = RAISED, bd = 4, **kw) #Create the frame that will parent the frames for each tab
self.noteBook.grid_propagate(0) #self.noteBook has a bad habit of resizing itself, this line prevents that
Frame.__init__(self)
self.noteBookFrame.grid()
self.BFrame.grid(row =0, sticky = W)
self.noteBook.grid(row = 1, column = 0, columnspan = 27)
def change_tab(self, IDNum):
"""Internal Function"""
for i in (a for a in range(0, len(self.tabVars.keys()))):
if not i in self.deletedTabs: #Make sure tab hasen't been deleted
if i != IDNum: #Check to see if the tab is the one that is currently selected
self.tabVars[i][1].grid_remove() #Remove the Frame corresponding to each tab that is not selected
self.tabVars[i][0]['relief'] = self.inactiverelief #Change the relief of all tabs that are not selected to "Groove"
self.tabVars[i][0]['fg'] = self.inactivefg #Set the fg of the tab, showing it is selected, default is black
else: #When on the tab that is currently selected...
self.tabVars[i][1].grid() #Re-grid the frame that corresponds to the tab
self.tabVars[IDNum][0]['relief'] = self.activerelief #Change the relief to "Raised" to show the tab is selected
self.tabVars[i][0]['fg'] = self.activefg #Set the fg of the tab, showing it is not selected, default is black
def add_tab(self, width = 2, **kw):
"""Creates a new tab, and returns it's corresponding frame"""
temp = self.tabs #Temp is used so that the value of self.tabs will not throw off the argument sent by the label's event binding
self.tabVars[self.tabs] = [Label(self.BFrame, relief = RIDGE, **kw)] #Create the tab
self.tabVars[self.tabs][0].bind("<Button-1>", lambda Event:self.change_tab(temp)) #Makes the tab "clickable"
self.tabVars[self.tabs][0].pack(side = LEFT, ipady = self.ypad, ipadx = self.xpad) #Packs the tab as far to the left as possible
self.tabVars[self.tabs].append(Frame(self.noteBook, **self.kwargs)) #Create Frame, and append it to the dictionary of tabs
self.tabVars[self.tabs][1].grid(row = 0, column = 0) #Grid the frame ontop of any other already existing frames
self.change_tab(0) #Set focus to the first tab
self.tabs += 1 #Update the tab count
return self.tabVars[temp][1] #Return a frame to be used as a parent to other widgets
def destroy_tab(self, tab):
"""Delete a tab from the notebook, as well as it's corresponding frame"""
self.iteratedTabs = 0 #Keep track of the number of loops made
for b in self.tabVars.values(): #Iterate through the dictionary of tabs
if b[1] == tab: #Find the NumID of the given tab
b[0].destroy() #Destroy the tab's frame, along with all child widgets
self.tabs -= 1 #Subtract one from the tab count
self.deletedTabs.append(self.iteratedTabs) #Apend the NumID of the given tab to the list of deleted tabs
break #Job is done, exit the loop
self.iteratedTabs += 1 #Add one to the loop count
def focus_on(self, tab):
"""Locate the IDNum of the given tab and use
change_tab to give it focus"""
self.iteratedTabs = 0 #Keep track of the number of loops made
for b in self.tabVars.values(): #Iterate through the dictionary of tabs
if b[1] == tab: #Find the NumID of the given tab
self.change_tab(self.iteratedTabs) #send the tab's NumID to change_tab to set focus, mimicking that of each tab's event bindings
break #Job is done, exit the loop
self.iteratedTabs += 1 #Add one to the loop count
def NotebookView():
root = Tk()
root.title("Yearly Budget Comparison by Month")
note = Notebook(root, width= 400, height =600, activefg = 'red', inactivefg = 'blue') #Create a Note book Instance
note.grid()
tab1 = note.add_tab(text = " January")
tab2 = note.add_tab(text = " February")
tab3 = note.add_tab(text = "March ") #Create a tab with the text "March"
tab4 = note.add_tab(text = " April")
tab5 = note.add_tab(text = "May ")
tab6 = note.add_tab(text = " June")
tab7 = note.add_tab(text = " July")
tab8 = note.add_tab(text = "August ")
tab9 = note.add_tab(text = " September")
tab10 = note.add_tab(text = " October")
tab11 = note.add_tab(text = "November ")
tab12 = note.add_tab(text = " December")
Label(tab1, text = 'January Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 1,pady = 25,padx = 25)
Label(tab2, text = 'Febuary Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab3, text = 'March Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab4, text = 'April Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab5, text = 'May Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab6, text = 'June Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab7, text = 'July Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab8, text = 'August Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab9, text = 'September Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab10, text = 'October Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab11, text = 'November Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
Label(tab12, text = 'December Monthly Budget Comparison:',font =("Comic Sans MS", 14, "italic"),fg = 'RED',justify = CENTER).grid(row = 0, column = 7,pady = 25)
T2.CreateTreeview=ttk.Treeview(tab1,height = 20).grid(row = 4, column = 1, columnspan = 6)
note.focus_on(tab1)
root.mainloop()
if __name__ == "__main__":
NotebookView()
Without going through all of the code, there is one very clear problem: you are creating two instances of Tk, and calling mainloop twice. Within a single GUI you should only ever create exactly once instance, and call mainloop exactly once.

Resources