Python Tkinter - Get value from mutliple checkboxes - python-2.7

I am creating a Tkinter application where trying to get value from multiple checkboxes. I am able to create the checkboxes but not able to retrieve the value .i.e. checked or not checked checkboxes.
Requirement:
I need to loop through all checkbox variables to identify the checked ones.
import openpyxl
import sys
import pandas as pd
from Tkinter import *
import ttk
import tkFont
reload(sys)
sys.setdefaultencoding('utf8')
top = Tk()
notebook = ttk.Notebook(top)
notebook.grid(row=1, column=0, columnspan=1, sticky=W)
frame1 = ttk.Frame(top)
notebook.add(frame1, text='TAB1')
s = ttk.Style()
s.theme_use('clam')
helv36 = tkFont.Font(family='Helvetica', size=12, weight=tkFont.BOLD)
wb = openpyxl.load_workbook('File',data_only=True)
ws = wb['Sheet1']
mylist = []
mylist1 = []
for col in ws['A']:
mylist.append(col.value)
for col in ws['B']:
mylist1.append(col.value)
mylist = [str(item) for item in mylist]
mylist1 = [str(item) for item in mylist1]
i=2
for name in mylist:
Label(frame1, text="col1",
borderwidth=1,font=helv36).grid(row=1)
Label(frame1, text=name,
borderwidth=1).grid(row=i)
i +=1
i =2
for name in mylist1:
Label(frame1, text="col2",
borderwidth=1,font=helv36).grid(row=1, column=1)
Label(frame1, text=name,
borderwidth=1).grid(row=i,column=1)
val = IntVar()
val = "v" + str(i)
c_val = Checkbutton(frame1, variable=val)
c_val.grid(row=i, column=2,sticky = W)
i +=1
***def chkbox_checked():
#Need to loop to get checked checkboxes***
B200 = Button(frame1, text ="Check", command = chkbox_checked,font=helv36, bg='orange')
B200.grid(row=100)
top.mainloop()

You can associate a BooleanVar to the checkbox and get the value. You can then use set() method to set the default value for the checkbox and get() to get the state of the checkbox. For example:
import tkinter as tk
root=tk.Tk()
c=tk.BooleanVar()
tk.Checkbutton(root,variable=c,command=lambda: print(c.get())).pack()
root.mainloop()
if you want to loop over a number of checkboxes, you can do this:
import tkinter as tk
root=tk.Tk()
c1=tk.BooleanVar()
c2=tk.BooleanVar()
c3=tk.BooleanVar()
c4=tk.BooleanVar()
def get_value():
for c in (c1,c2,c3,c4):
print(c.get())
tk.Checkbutton(root,text='checkbox1',variable=c1,).pack()
tk.Checkbutton(root,text='checkbox2',variable=c2,).pack()
tk.Checkbutton(root,text='checkbox3',variable=c3,).pack()
tk.Checkbutton(root,text='checkbox4',variable=c4,).pack()
tk.Button(root,text='get value',command=get_value).pack()
root.mainloop()

Related

want to create two label in tkinter gui window and display continous counting value:

i have written a code for that its working and window popped up with two label but values are not incremented::i am quite new to python ,please help me out to resolve ...
thanks in advance..
import Tkinter
import time
root = Tkinter.Tk()
var = Tkinter.IntVar()
var1 = Tkinter.IntVar()
label1 = Tkinter.Label(root, textvariable=var)
label2 = Tkinter.Label(root, textvariable=var1)
root.geometry("200x200")
label1.pack()
label2.pack()
def function():
while 1:
i=0
j=0
i += 1
var.set(i)
#time.sleep(1)
var1.set(j)
j += 1
root.update()
#time.sleep(1)
root.after(10, function)
root.update()
root.mainloop()
Do you want your counters to be automatically incremented as time goes by? If yes, the easiest solution is to reuse the after method at the end of your function():
import Tkinter as tk
def function():
var1.set(var1.get()+1)
var2.set(var2.get()+1)
root.after(100, function)
root = tk.Tk()
root.geometry("200x200")
var1 = tk.IntVar()
var2 = tk.IntVar()
label1 = tk.Label(root, textvariable=var1)
label2 = tk.Label(root, textvariable=var2)
label1.pack()
label2.pack()
root.after(10, function)
root.mainloop()

python 2.7 program to extract data from excel workbooks - why does it need to be saved in the same folder as the files?

I've got a program that uses openpyxl, os and tkinter that lets a person choose a file directory and then extracts data from certain cells from excel files in that directory. As-is, it will only run if the python file is in the same folder as the files from which data is being extracted are located.
I want to make it so that the program file can be stored outside that folder, but I can't figure out why it needs to be within that folder based on my code. Can someone point me to the place in the code that is making this be necessary?
Thank you
#!/usr/bin/env python
import os
import openpyxl
import Tkinter as tk
from Tkinter import *
import tkFileDialog, tkMessageBox, ttk
def file_open():
file_path = tkFileDialog.askdirectory()
if file_path == "":
tkMessageBox.showinfo("Error", "No Folder Selected")
else:
ALL_SHEETS = [f for f in os.listdir(file_path)
if os.path.isfile(os.path.join(file_path, f))
and f.endswith('.xlsx')]
HEAD = 1
ROW = 2
START = 1
END = 11
OUTFILE = 'empty_book.xlsx'
def get_row(sht, start, end, row):
row_data = []
for col in range(start, end):
d = sht.cell(row=row, column=col)
row_data.append(d.value)
return row_data
def get_all(files):
data_rows = []
for f in files:
wb = openpyxl.load_workbook(filename=f, data_only=True)
sheet = wb.get_sheet_by_name('Data')
row = get_row(sheet, START, END, ROW)
data_rows.append(row)
return data_rows
def get_headings(sheets):
first = sheets[1]
wb = openpyxl.load_workbook(filename=first)
sheet = wb.get_sheet_by_name('Data')
row = get_row(sheet, START, END, HEAD)
return row
def write_new(header, data, f):
wb = openpyxl.Workbook()
ws1 = wb.active
ws1.title = 'Data'
ws1.append(header)
for row in data:
ws1.append(row)
wb.save(filename=f)
def together():
sheets = sorted(ALL_SHEETS)
header = get_headings(sheets)
data = get_all(sheets)
write_new(header, data, OUTFILE)
together()
tkMessageBox.showinfo("Great Job!", "Data Extraction Successful!")
class NSC(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.parent.title("Degree Planner Data Extractor")
l1 = tk.Label(text="Degree Planner Data Extractor", font=('Segui',
20))
l1.place(x = 35, y = 20)
nscButton = tk.Button(text=' Extract data from degree planners ',
command=file_open)
nscButton.place(x= 80, y=100)
quitButton = tk.Button(text=" Quit ", command=self.quit)
quitButton.place(x=155, y=155)
def main():
root = Tk()
w = 400
h = 250
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
root.resizable(0,0)
app = NSC(root)
root.mainloop()
if __name__ == '__main__':
main()
You've kinda solved the problem in your code already. os.listdir returns file names without path so you needed os.path.join for the isfile test. You need to add that joined name to your list.
ALL_SHEETS = [os.path.join(file_path, f) for f in os.listdir(file_path)
if os.path.isfile(os.path.join(file_path, f))
and f.endswith('.xlsx')]
glob.glob does almost the same thing with the small risk that somebody named a directory ".xlsx".
from glob import glob
ALL_SHEETS = [f for f in glob(os.path.join(file_path, "*.xlsx"))
if os.path.isfile(f)]]

cannot get response from Bokeh RadioButtonGroup

I am trying to understand how to use interactivity in RadioButtonGroup using Bokeh and CustomJS with a Python function. I have tweaked the example provided at the Bokeh site for plotting y=x^f. Instead of using a slider for the power f, I would like to toggle between two powers, f=0.5 and f=0.2. I have followed the manual and inserted RadioButtonGroup in my code using Jupyter notebook. The buttons are showing and responsive, but I am unable to get any callback response out of toggling the buttons.
Any help will be appreciated.
from math import pi
from bokeh.io import output_file, show
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS, Slider, TextInput, RadioButtonGroup
from bokeh.plotting import Figure, output_notebook
output_notebook()
x = [x*0.005 for x in range(0, 200)]
y = x
source = ColumnDataSource(data=dict(x=x, y=y))
plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
def callback(source=source, input1=input1, window=None):
data = source.data
m= input1.active
if m==0:
f=.5
else:
f=2
x, y = data['x'], data['y']
for i in range(len(x)):
y[i] = window.Math.pow(x[i], f)
source.trigger('change')
input1 = RadioButtonGroup(labels=["power = .5", "power = 2."], active=0)
input1.button_type="success"
input1.js_on_change('active', CustomJS.from_py_func(callback))
layout = column(input1, plot)
show(layout)
I can not make bokeh.models.RadioButtonGroup generate a callback, but with bokeh.models.RadioGroup I can (I'm using bokeh version 0.12.4 Maybe a newer version facilitates RadioButtonGroup to generate a callback). Also, you are referencing input1 before declaring it. It's not needed as input of your callback function, inside you can use cb_obj. See:
import bokeh
import bokeh.plotting
bokeh.io.output_notebook()
x = [x*0.005 for x in range(0, 200)]
y = x
source = bokeh.models.ColumnDataSource(data=dict(x=x, y=y))
plot = bokeh.plotting.figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
def callback(source=source, window=None):
data = source.data
m = cb_obj.active
if m==0:
f=.5
else:
f=2
x, y = data['x'], data['y']
for i in range(len(x)):
y[i] = window.Math.pow(x[i], f)
source.trigger('change')
input1 = bokeh.models.RadioGroup(labels=["power = .5", "power = 2."],active=0,
callback=bokeh.models.CustomJS.from_py_func(callback))
layout = bokeh.layouts.column(input1, plot)
bokeh.io.show(layout)

Curdoc() keeps adding plots, want to replace

I have written a program that creates a graph based on input from a dropdown list. I am using curdoc().add_root() from bokeh to show my graphs on a server as show() does not work. However, whenever I choose a new option, instead of replacing the current graph, it creates one below it. I have tried curdoc().clear() its not working. How do I make this work where it replaces the graph but doesnt delete the dropdown list, because that is what curdoc().clear() is doing? Here's my code:
import csv
import bokeh.plotting
from bokeh.plotting import figure, curdoc
from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models.widgets import MultiSelect
from bokeh.io import output_file, show, vform
from bokeh.layouts import row
from collections import defaultdict
columns = defaultdict(list) # each value in each column is appended to a list
columns1 = defaultdict(list)
with open('my_data.csv') as f:
for row in f:
row = row.strip()# read a row as {column1: value1, column2: value2,...}
row = row.split(',')
columns[row[0]].append(row[1])
columns[row[0]].append(row[2])
columns[row[0]].append(row[3])
columns[row[0]].append(row[4])
columns[row[0]].append(row[5])
with open('my_data1.csv') as f:
for row in f:
row = row.strip()# read a row as {column1: value1, column2: value2,...}
row = row.split(',')
columns1[row[0]].append(row[1])
columns1[row[0]].append(row[2])
columns1[row[0]].append(row[3])
columns1[row[0]].append(row[4])
columns1[row[0]].append(row[5])
from bokeh.layouts import widgetbox
from bokeh.models.widgets import Dropdown
from bokeh.plotting import curdoc
menu = [("NY", "New York"), ("California", "California"), ("Ohio", "Ohio")]
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)
count = 0
#def function_to_call(attr, old, new):
#print dropdown.value
def myfunc(attr, old, new):
aaa = dropdown.value
xy = (columns[aaa])
xy = [float(i) for i in xy]
myInt = 10000
xy = [x / myInt for x in xy]
print xy
omega = (columns1[aaa])
omega = [float(i) for i in omega]
print omega
import numpy
corr123 = numpy.corrcoef(omega,xy)
print corr123
a = [2004, 2005, 2006, 2007, 2008]
p = figure(tools="pan,box_zoom,reset,save", title="Diabetes and Stats",
x_axis_label='Years', y_axis_label='percents')
# add some renderers
per = "Diabetes% " + aaa
p.line(a, omega, legend=per)
p.circle(a, omega, legend=per, fill_color="white",line_color="green", size=8)
p.line(a, xy, legend="Per Capita Income/10000")
p.circle(a, xy, legend="Per Capita Income/10000", fill_color="red", line_color="red", size=8)
p.legend.location="top_left"
#bokeh.plotting.reset_output
#curdoc().clear()
curdoc().add_root(p)
curdoc().add_root(dropdown)
#bokeh.plotting.reset_output
dropdown.on_change('value', myfunc)
curdoc().add_root(dropdown)

How to get a graph for stock market analysis?

I updated the code and it now provides the graph, however after giving me the graph it produces the following error messages.
Warning (from warnings module):
File "C:\Python27\lib\site-packages\matplotlib\collections.py", line 590
if self._edgecolors == str('face'):
FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
import urllib2
import time
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
from matplotlib.finance import candlestick_ochl
import matplotlib
import pylab
matplotlib.rcParams.update({'font.size': 9})
def rsiFunc(prices, n=14):
deltas = np.diff(prices)
seed = deltas[:n+1]
up = seed[seed>=0].sum()/n
down = -seed[seed<0].sum()/n
rs = up/down
rsi = np.zeros_like(prices)
rsi[:n] = 100. - 100./(1.+rs)
for i in range(n, len(prices)):
delta = deltas[i-1] # cause the diff is 1 shorter
if delta>0:
upval = delta
downval = 0.
else:
upval = 0.
downval = -delta
up = (up*(n-1) + upval)/n
down = (down*(n-1) + downval)/n
rs = up/down
rsi[i] = 100. - 100./(1.+rs)
return rsi
def movingaverage(values,window):
weigths = np.repeat(1.0, window)/window
smas = np.convolve(values, weigths, 'valid')
return smas # as a numpy array
def ExpMovingAverage(values, window):
weights = np.exp(np.linspace(-1., 0., window))
weights /= weights.sum()
a = np.convolve(values, weights, mode='full')[:len(values)]
a[:window] = a[window]
return a
def computeMACD(x, slow=26, fast=12):
"""
compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg'
return value is emaslow, emafast, macd which are len(x) arrays
"""
emaslow = ExpMovingAverage(x, slow)
emafast = ExpMovingAverage(x, fast)
return emaslow, emafast, emafast - emaslow
def graphData(stock,MA1,MA2):
'''
Use this to dynamically pull a stock:
'''
try:
print 'Currently Pulling',stock
print str(datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d %H:%M:%S'))
#Keep in mind this is close high low open data from Yahoo
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv'
stockFile =[]
try:
sourceCode = urllib2.urlopen(urlToVisit).read()
splitSource = sourceCode.split('\n')
for eachLine in splitSource:
splitLine = eachLine.split(',')
if len(splitLine)==6:
if 'values' not in eachLine:
stockFile.append(eachLine)
except Exception, e:
print str(e), 'failed to organize pulled data.'
except Exception,e:
print str(e), 'failed to pull pricing data'
try:
date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile,delimiter=',', unpack=True,
converters={ 0: mdates.strpdate2num('%Y%m%d')})
x = 0
y = len(date)
newAr = []
while x < y:
appendLine = date[x],openp[x],closep[x],highp[x],lowp[x],volume[x]
newAr.append(appendLine)
x+=1
Av1 = movingaverage(closep, MA1)
Av2 = movingaverage(closep, MA2)
SP = len(date[MA2-1:])
fig = plt.figure(facecolor='#07000d')
ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4, axisbg='#07000d')
candlestick_ochl(ax1, newAr[-SP:], width=.6, colorup='#53c156', colordown='#ff1717')#width=.6, plot_day_summary_ohlc
Label1 = str(MA1)+' SMA'
Label2 = str(MA2)+' SMA'
ax1.plot(date[-SP:],Av1[-SP:],'#e1edf9',label=Label1, linewidth=1.5)
ax1.plot(date[-SP:],Av2[-SP:],'#4ee6fd',label=Label2, linewidth=1.5)
ax1.grid(True, color='w')
ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax1.yaxis.label.set_color("w")
ax1.spines['bottom'].set_color("#5998ff")
ax1.spines['top'].set_color("#5998ff")
ax1.spines['left'].set_color("#5998ff")
ax1.spines['right'].set_color("#5998ff")
ax1.tick_params(axis='y', colors='w')
plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper')) #gca()
ax1.tick_params(axis='x', colors='w')
plt.ylabel('Stock price and Volume')
maLeg = plt.legend(loc=9, ncol=2, prop={'size':7},
fancybox=True, borderaxespad=0.)
maLeg.get_frame().set_alpha(0.4)
textEd = plt.gca().get_legend().get_texts()#pylab.gca() changed to plt.gca()
plt.setp(textEd[0:5], color = 'w')#changed pylab.setp to plt.setp
volumeMin = 0
ax0 = plt.subplot2grid((6,4), (0,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')
rsi = rsiFunc(closep)
rsiCol = '#c1f9f7'
posCol = '#386d13'
negCol = '#8f2020'
ax0.plot(date[-SP:], rsi[-SP:], rsiCol, linewidth=1.5)
ax0.axhline(70, color=negCol)
ax0.axhline(30, color=posCol)
ax0.fill_between(date[-SP:], rsi[-SP:], 70, where=(rsi[-SP:]>=70), facecolor=negCol, edgecolor=negCol, alpha=0.5)
ax0.fill_between(date[-SP:], rsi[-SP:], 30, where=(rsi[-SP:]<=30), facecolor=posCol, edgecolor=posCol, alpha=0.5)
ax0.set_yticks([30,70])
ax0.yaxis.label.set_color("w")
ax0.spines['bottom'].set_color("#5998ff")
ax0.spines['top'].set_color("#5998ff")
ax0.spines['left'].set_color("#5998ff")
ax0.spines['right'].set_color("#5998ff")
ax0.tick_params(axis='y', colors='w')
ax0.tick_params(axis='x', colors='w')
plt.ylabel('RSI')
ax1v = ax1.twinx()
ax1v.fill_between(date[-SP:],volumeMin, volume[-SP:], facecolor='#00ffe8', alpha=.4)
ax1v.axes.yaxis.set_ticklabels([])
ax1v.grid(False)
ax1v.set_ylim(0, 3*volume.max())
ax1v.spines['bottom'].set_color("#5998ff")
ax1v.spines['top'].set_color("#5998ff")
ax1v.spines['left'].set_color("#5998ff")
ax1v.spines['right'].set_color("#5998ff")
ax1v.tick_params(axis='x', colors='w')
ax1v.tick_params(axis='y', colors='w')
ax2 = plt.subplot2grid((6,4), (5,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')
# START NEW INDICATOR CODE #
# END NEW INDICATOR CODE #
plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
ax2.spines['bottom'].set_color("#5998ff")
ax2.spines['top'].set_color("#5998ff")
ax2.spines['left'].set_color("#5998ff")
ax2.spines['right'].set_color("#5998ff")
ax2.tick_params(axis='x', colors='w')
ax2.tick_params(axis='y', colors='w')
ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))
for label in ax2.xaxis.get_ticklabels():
label.set_rotation(45)
plt.suptitle(stock.upper(),color='w')
plt.setp(ax0.get_xticklabels(), visible=False)
plt.setp(ax1.get_xticklabels(), visible=False)
'''ax1.annotate('Big news!',(date[510],Av1[510]),
xytext=(0.8, 0.9), textcoords='axes fraction',
arrowprops=dict(facecolor='white', shrink=0.05),
fontsize=14, color = 'w',
horizontalalignment='right', verticalalignment='bottom')'''
plt.subplots_adjust(left=.09, bottom=.14, right=.94, top=.95, wspace=.20, hspace=0)
plt.show()
fig.savefig('example.png',facecolor=fig.get_facecolor())
except Exception,e:
print 'main loop',str(e)
while True:
stock = raw_input('Stock to plot: ')
graphData(stock,10,50)
Please look at the thread Violin plot: warning with matplotlib 1.4.3 and pyplot fill_between warning since upgrade of numpy to 1.10.10
It seems there is a bug in matplotlib 1.4.3 (which has only started causing that error since the upgrade to numpy 1.10). This is reportedly corrected in 1.5.0 (which should be released soon). Hope this helps.