Okay so I wrote this code...
#!/usr/bin/env
import sys
import time
import subprocess
from Tkinter import *
import numpy
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib
import matplotlib.pyplot as plt
import threading
CDatei = subprocess.Popen("/home/pi/meinc++/Spi")
print("Hallo")
i = 0
x = 0
def GetValue():
with open("/home/pi/meinc++/BeispielDatei.txt","r") as Datei:
for line in Datei:
time.sleep(0.01)
return line
def WithoutNull(input):
ReturnValue = input
while ReturnValue is None:
ReturnValue = GetValue()
return ReturnValue
def UebergabeWert():
while x == 0:
WholeString = WithoutNull(GetValue())
StringVar, DatumVar = WholeString.strip().split(' - ')
IntStringVar = [int(v) for v in StringVar.split()]
return IntStringVar, DatumVar
def MinutenWert():
Maximum = 0
Minimum = 0
i = 0
LaengeArray = 0
Multiplikator = 10000
ArrayValue = [-999999]*Multiplikator
AlteZeit = time.time()
while 1:
CompleteValue, Trash = UebergabeWert()
ArrayValue[i] = CompleteValue[0]
i = i + 1
ArrayFilter = filter(lambda c: c != -999999,ArrayValue)
ArraySumme = numpy.sum(ArrayFilter)
LaengeArray = len(ArrayFilter)
Mittelwert = ArraySumme/LaengeArray
ArraySortierung = sorted(ArrayFilter)
Maximum = ArraySortierung[LaengeArray-1]
Minimum = ArraySortierung[0]
NeueZeit = time.time()
if NeueZeit-AlteZeit >= 60:
AlteZeit = time.time()
ArrayValue[i:Multiplikator] = [-999999]*(Multiplikator-i)
i = 0
yield Mittelwert
yield Maximum
yield Minimum
yield LaengeArray
yield ArrayFilter
def UebergabeTkinter():
while 1:
Mittelwert = next(MinutenWertYield)
Maximum = next(MinutenWertYield)
Minimum = next(MinutenWertYield)
LaengeArray = next(MinutenWertYield)
ArrayFilter = next(MinutenWertYield)
CompleteValue, DatumVar = UebergabeWert()
Variable1.set(CompleteValue[0])
Variable2.set(CompleteValue[1])
Variable3.set(CompleteValue[2])
Variable4.set(CompleteValue[3])
VariableMittelwert.set(Mittelwert)
VariableMaximum.set(Maximum)
VariableMinimum.set(Minimum)
t = threading.Thread(target = Grafik)
t.start()
root.update()
def Grafik():
GrafikAnfang = time.time()
Array = 0
ArrayGrafik = [0]*20
GrafikEnde = 1
while 1:
CompleteValue, DatumVar = UebergabeWert()
ArrayGrafik[Array] = CompleteValue[0]
LaengeArrayGrafik = len(ArrayGrafik)
fig = Figure(figsize = (3, 3))
axis = fig.add_subplot(111)
axis.legend()
axis.grid()
canvas = FigureCanvasTkAgg(fig, master = root)
canvas.get_tk_widget().grid(row=10,column=0,rowspan=2,columnspan=2)
LinienBreite = numpy.linspace(1,LaengeArrayGrafik,LaengeArrayGrafik)
axis.plot(LinienBreite,ArrayGrafik,'b-')
axis.set_xticks(LinienBreite)
DatumArray = [DatumVar]
axis.set_xticklabels(DatumArray)
canvas.draw()
fig.clear()
print Array
if GrafikEnde-GrafikAnfang < 600:
Array = Array + 1
GrafikEnde = time.time()
if GrafikEnde-GrafikAnfang >= 600:
del ArrayGrafik[0]
def Exit():
root.destroy()
return
try:
MinutenWertYield = MinutenWert()
root = Tk()
Leiste = Menu(root)
root.config(menu = Leiste)
DateiMenu = Menu(Leiste)
Leiste.add_cascade(label = "datei", menu = DateiMenu)
DateiMenu.add_command(label = "Exit", command = Exit)
EditMenu = Menu(Leiste)
Leiste.add_cascade(label = "edit", menu = EditMenu)
Variable1 = IntVar()
Variable2 = IntVar()
Variable3 = IntVar()
Variable4 = IntVar()
VariableMittelwert = IntVar()
VariableMaximum = IntVar()
VariableMinimum = IntVar()
Ausgang = 0
for column in range(0,8,2):
String1 = "Ausgang "
String1 += `Ausgang`
Ausgang = Ausgang + 1
Label(text = String1).grid(row=0,column=column)
Ausgang = 0
for column in range(0,8,2):
String1 = "Der Wert von "
String2 = " ist: "
String1 += `Ausgang`
Ausgang = Ausgang + 1
String3 = String1+String2
Label(text = String3).grid(row=2,column=column)
Label(text = "Der Mittelwert ist: ").grid(row=4,column=0)
Label(text = "Das Maximum ist: ").grid(row=5,column=0)
Label(text = "Das Mimimum ist: ").grid(row=6,column=0)
Label1 = Label(root, textvariable = Variable1)
Label1.grid(row = 2, column = 1)
Label2 = Label(root, textvariable = Variable2)
Label2.grid(row = 2, column = 3)
Label3 = Label(root, textvariable = Variable3)
Label3.grid(row = 2, column = 5)
Label4 = Label(root, textvariable = Variable4)
Label4.grid(row = 2, column = 7)
LabelMittelwert = Label(root, textvariable = VariableMittelwert)
LabelMittelwert.grid(row = 4, column = 1)
LabelMaximum = Label(root, textvariable = VariableMaximum)
LabelMaximum.grid(row = 5, column = 1)
LabelMinimum = Label(root, textvariable = VariableMinimum)
LabelMinimum.grid(row = 6, column = 1)
UebergabeTkinter()
print "Hallo"
root.mainloop()
except KeyboardInterrupt:
CDatei.kill()
root.quit()
root.destroy()
and when i run it, it says "RuntimeError: main thread is not in the main loop".
Short explanation of the code: It's a code to read out sensor data from a text file -
GetValue().
If the Data is Null it'll read out again - WithoutNull().
The Data is then splitted into data and timestamp (cause it has the format val1, val2, val3, val4, time) - UebergabeWert.
Then the maxima, minima and average of the data will be measured - MinutenWert()
After this, the values are set as labels and go their way into Tkinter - UebergabeTkinter()
The Tkinter build is mainly in Try:
What I wanted to do there, is to implement a graph to Tkinter, but because of the fast changing values it got tremendously slow so i decided to put the graph build in a thread and run it parallel to Tkinter. Unfortunately, it doesn't seem to work and I don't know why
Any suggestions?
Related
I am writing an application for a digital lab balance that connects over serial. To build the application I set up a COM port bridge and wrote a program to simulate the balance on my machine (the balance was in use). I will show you the most recent version of the balance simulation program:
import serial, random, time
s = serial.Serial('COM2')
#Initially we will just push a random float
#After the data the scale sends a carraige return + line feed
def pushData():
data = f'{round(random.uniform(10, 100), 2)}\r\n'.encode()
print(f'Sending Data: {data}')
s.write(data)
try:
while True:
pushData()
time.sleep(10)
except:
print('Something went wrong.')
This code along with my balance application works as expected on my machine. But when I try to use my balance program with the actual device it does not get all the serial data if it even works at all. I am wondering if I need some kind of multi-threading, if its a timing issue or something. I know the balance works because I can monitor the COM port.
I will post my most recent balance program here:
# !/usr/bin/python3
################ Imports
import serial, pyperclip
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from datetime import datetime, time
from tkinter import *
################ Declarations
GUI = Tk()
s = serial.Serial('COM5', timeout=1)
wgtList = [0,0,0,0,0]
wgtDict = {'Lab':[],
'Weight':[]}
newL = '\r\n'
tareWgt = 0
newWgt = 0 #Trying to get past program not working when no data is pushed
################ Functions
def thisAfter():
"""Updates scale feed and updates the scale feed."""
try:
global newWgt
newWgt = float(s.readline().decode().rstrip('\r\n')) - tareWgt
except ValueError:
#print('ValueError thisAfter(): NO DATA OR COULD NOT CONVERT SERIAL DATA TO FLOAT')
print('ValueError thisAfter(): '+ str(newWgt))
print('wgtList: '+ str(wgtList))
wgtList.append(newWgt)
if newWgt not in wgtList[0:5]:
text.insert(INSERT,str(newWgt)+newL)
if len(wgtList) > 5:
del wgtList[0]
GUI.after(50, thisAfter)
text.see(END)
def labCallback():
"""Saves data to file, iterates the entry field."""
num = labEntry.get()
csvStr = datetime.today().strftime("%Y/%m/%d") + ',' + datetime.now().strftime("%H:%M:%S") + ',' + num + ',' + str(wgtList[-1]) + ',' + var1.get() + ',' + str(tareWgt) + newL
with open('data.csv', 'a+', newline = '') as file:
if file.readline() == None:
file.write('Date, Time, Lab, Weight, Type' + newL)
file.write(csvStr)
#print(csvStr) #Just checking
labEntry.delete(0,END)
labEntry.insert(0, int(num) + 1)
csvArr = csvStr.split(',')
wgtDict['Lab'].append(int(csvArr[2]))
wgtDict['Weight'].append(float(csvArr[3]))
text2.insert(INSERT, ',\t'.join(csvArr))
text2.see(END)
#print(str(wgtDict)+'\n')
def tareCallback():
global tareWgt
tareWgt = wgtList[-1]
print(tareWgt)
text3.insert(INSERT,newL+str(tareWgt))
text3.see(END)
def copyData():
global newWgt
pyperclip.copy(newWgt)
def close():
s.close()
def start():
global s
try:
s = serial.Serial('COM5', timeout=1)
thisAfter()
except:
print('Serial port closed')
################ Frames/Panes
frame1 = LabelFrame(GUI, text = 'Lab Label + Entry Field')
frame1.pack(side = TOP)
frame6 = LabelFrame(frame1, text = 'Tare')
frame6.pack(side = BOTTOM)
frame2 = LabelFrame(GUI, text = 'Scale Feed')
frame2.pack(side = BOTTOM)
frame3 = LabelFrame(GUI, text = 'Saved Feed')
frame3.pack(side = BOTTOM)
frame4 = LabelFrame(GUI, text = 'Plot')
frame4.pack(side = TOP)
frame5 = LabelFrame(frame1, text = 'Type Select')
frame5.pack(side = BOTTOM)
################ Lab Label + Entry Field + Type Select
labLabel = Label(frame1, bd = 5, text = 'Lab#')
labLabel.pack(side = LEFT)
tareLabel = Label(frame6, bd = 5, text = 'Tare')
tareLabel.pack(side = LEFT)
text3 = Text(frame6, height = 1, width = 20)
text3.pack(side = RIGHT)
closeButton = Button(frame1, text = 'Close', command = close)
closeButton.pack(side = RIGHT)
startButton = Button(frame1, text = 'Start', command = start)
startButton.pack(side = RIGHT)
tareButton = Button(frame1, text = 'Tare', command = tareCallback)
tareButton.pack(side = RIGHT)
undoButton = Button(frame1, text = 'Undo')
undoButton.pack(side = RIGHT)
labButton = Button(frame1, text = 'Save', command = labCallback)
labButton.pack(side = RIGHT)
copyButton = Button(frame1, text = 'Copy', command = copyData)
copyButton.pack(side = RIGHT)
labEntry = Entry(frame1)
labEntry.pack(side = RIGHT)
var1 = StringVar()
r1 = Radiobutton(frame5, text = 'pH', variable= var1, value = 'pH')
r1.pack(anchor = 's')
r2 = Radiobutton(frame5, text = 'pH-Tray', variable= var1, value = 'pH-Tray')
r2.pack(anchor = 's')
r3 = Radiobutton(frame5, text = 'Mehlich', variable= var1, value = 'Mehlich')
r3.pack(anchor = 's')
r4 = Radiobutton(frame5, text = 'Nitrate', variable= var1, value = 'Nitrate')
r4.pack(anchor = 's')
r5 = Radiobutton(frame5, text = 'Excel', variable= var1, value = 'Excel')
r5.pack(anchor = 's')
r6 = Radiobutton(frame5, text = 'Excel-Tray', variable= var1, value = 'Excel-Tray', state=DISABLED)
r6.pack(anchor = 's')
r1.select()
r2.deselect()
r3.deselect()
r4.deselect()
r5.deselect()
r6.deselect()
################ Scale Feed
scrollbar = Scrollbar(frame2)
scrollbar.pack(side = RIGHT, fill = Y)
text = Text(frame2, yscrollcommand = scrollbar.set, height = 10)
text.pack()
text.bind('<ButtonPress>', lambda e: 'break')
scrollbar.config(command = text.yview)
#thisAfter()
################ Saved Feed
scrollbar = Scrollbar(frame3)
scrollbar.pack(side = RIGHT, fill = Y)
text2 = Text(frame3, yscrollcommand = scrollbar.set, height = 10)
text2.pack()
scrollbar.config(command = text.yview)
################ Plot
f = plt.Figure(dpi=50, figsize=(13, 4))
plt.xkcd()
a = f.add_subplot(111)
def animate(i):
xL = wgtDict['Lab']
yL = wgtDict['Weight']
a.clear()
a.plot(xL, yL)
canvas = FigureCanvasTkAgg(f, frame4)
canvas.get_tk_widget().pack(side = LEFT, fill = BOTH)
ani = animation.FuncAnimation(f, animate, interval=1000)
# This is some kind of 'while true' loop fyi
GUI.mainloop()
Iam complete new to python,
this code i've been following steps from a book "python GUI programing cookbook "
the GUI works fine , but the methods wont work please help :
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import messagebox as mBox
from tkinter import Spinbox
class OOP:
def __init__(self):
self.win=tk.Tk()
self.win.title("silver and gold")
self.win.iconbitmap(r'E:\hydra-logo.ico')
self.GUI()
def click_me(self):
self.action.configure(text = "item has been added-- "+ self.matrial.get()+self.weight.get())
def quit(self):
self.win.quit()
self.win.destroy()
exit()
def msgbox(self):
answer=mBox.askyesno('','are you satisfied ? ')
if answer==True:
print("+1 satisfied ")
else:
print("+1 unsatisfied ")
def spin(self):
value= self.spin.get()
print(value)
self.scr.insert(tk.INSERT,value+'\n')
def GUI(self):
tabcontrol=ttk.Notebook(self.win)
tab1=ttk.Frame(tabcontrol)
tabcontrol.add(tab1,text = 'Entry')
tab2=ttk.Frame(tabcontrol)
tabcontrol.add(tab2,text = "Storage")
tab3=ttk.Frame(tabcontrol)
tabcontrol.add(tab3,text = "customers")
tab3=tk.Frame(tab3,bg = 'blue')
tab3.pack()
tabcontrol.pack(expand = 1,fill = "both")
safezone=ttk.LabelFrame(tab1,text = 'my comfort zone')
safezone.grid(column = 0,row = 0)
mBox.showinfo('',"Running ")
## my safe zone
storage=ttk.LabelFrame(tab2,text = 'your storage is here')
storage.grid(column = 0,row = 0)
for orangecolor in range(2):
canvas=tk.Canvas(tab3,width = 150,height = 80,highlightthickness = 0,bg = 'orange')
canvas.grid(row = orangecolor,column = orangecolor)
menuBar=Menu(self.win)
self.win.config(menu = menuBar)
fileMenu=Menu(menuBar,tearoff = 0)
HelpMenu=Menu(menuBar,tearoff = 0)
menuBar.add_cascade(label = "File",menu = fileMenu)
menuBar.add_cascade(label = "Help",menu = HelpMenu)
HelpMenu.add_command(label = "About",command = self.msgbox)
fileMenu.add_command(label = "New")
fileMenu.add_command(label = "Exit",command = quit)
fileMenu.add_checkbutton(label = "Night Mode")
labelsFrame=ttk.LabelFrame(storage,text = "made by essam")
labelsFrame.grid(column = 0,row = 9,padx = 10,pady = 0)
ttk.Label(safezone,text = "Choose a metal: ").grid(column = 0,row = 0)
ttk.Label(safezone,text = "type the weight: ").grid(column = 1,row = 0,sticky = 'W')
weight=tk.StringVar()
wightEntered=ttk.Entry(safezone,width = 12,textvariable = weight)
wightEntered.grid(column = 1,row = 1)
wightEntered.focus()
matrial=tk.StringVar()
matrialEntered=ttk.Combobox(safezone,width = 12,textvariable = matrial,state = 'readonly')
matrialEntered.grid(column = 0,row = 1)
matrialEntered [ 'values' ]=("Gold","silver")
matrialEntered.current(0)
action=ttk.Button(safezone,text = "add ",command = self.click_me)
action.grid(column = 4,row = 1)
radVar=tk.IntVar()
radVar.set(99)
colors=[ "blue","gold","red" ]
spin=Spinbox(safezone,values = (1,2,4,42,100),width = 5,borderwidth = 20,
relief = tk.SUNKEN,command = self.spin)
spin.grid(column = 2,row = 1)
scrolW=30
scrolH=3
scr=scrolledtext.ScrolledText(safezone,width = scrolW,height = scrolH,wrap = tk.WORD)
scr.grid(column = 0,columnspan = 5,row = 7)
#******
oop =OOP()
oop.win.mainloop()
I am new to Tkinter. I'd like to write simple program and organize it using pack() method. Here is my code:
import Tkinter as tk
from Tkinter import *
import xlrd, os, sys, json
class Main():
def __init__(self):
global col, col1
self.master = tk.Tk()
self.master.title("Zliczanie ilosci spraw")
self.master.minsize(width=800, height=600)
plik = 'Aktualnie wybrany plik to: ' + 'Rejestr'
text = Label(self.master, text = plik)
text.pack(pady = 20)
self.wyswietlanie()
def wyswietlanie(self):
'''Funkcja, ktora zlicza i wyswietla ilosc spraw pracownikow'''
policzone_1 = []
policzone_2 = []
z = 0
dzial1 = {
"Pracownik1": "PRAC1",
"Pracownik2": "PRAC2"}
dzial2 = {
"Pracownik12": "PRAC12",
"Pracownik22": "PRAC22"}
for nazw in dzial1:
x = dzial1[nazw] #nazwisko z pliku excela
nazwisko = 0
policzone_1.append((nazw, nazwisko))
for nazw in dzial2:
x = dzial2[nazw] #nazwisko z pliku excela
nazwisko = 0
policzone_2.append((nazw, nazwisko))
posortowane1 = sorted(policzone_1,key=lambda x:x[1], reverse=True)
posortowane2 = sorted(policzone_2,key=lambda x:x[1], reverse=True)
dzial3 = Label(self.master)
dzial3.pack(side = LEFT)
dzial4 = Label(self.master)
dzial4.pack(side = LEFT)
for i in posortowane1:
wynik = '%s: %s' % (i[0], i[1])
dzial1 = Label(self.master, text = wynik, font = "Verdana 10 bold")
dzial1.pack(in_ = dzial3, padx = 200)
for i in posortowane2:
wynik = '%s: %s' % (i[0], i[1])
dzial2 = Label(self.master, text = wynik)
dzial2.pack(in_ = dzial4, padx = 200)
def run(self):
self.master.mainloop()
glowne = Main()
glowne.run()
Result is as on image below:
Why dzial1 and dzial2 are in these places (far from "text")? How can I organize dzial1, dzial2 (set them closer to each other)?
I am a fairly novice programmer and through coffee, google, and an immense loss of hair and fingernails have managed to write a very messy code. I am asking anyone to help me simplify the code if possible.
from tkinter import ttk
from tkinter import *
from tkinter.ttk import *
one = 0
why = 'Total Number: {}'
no = 0
clack = 0
click = 'Clicks: {}'
s = ttk.Style()
s.theme_use('clam')
s.configure('red.Vertical.TProgressbar', foreground = 'red', background = 'red')
s.configure('green.Vertical.TProgressbar', foreground = 'green', background = 'green')
s.configure('TButton', relief = 'groove')
def iround(x):
y = round(x) - .5
return int(y) + (y > 0)
class Application(ttk.Frame):
def __init__(self, master = None):
ttk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def Number(self):
global one
cost = 10*(self.w['to'])
if self.number['text'] == "Make Number go up":
self.number['text'] = one
if iround(self.w.get()) == 0:
one += 1
else:
one += iround(self.w.get())
self.number['text'] = one
if self.number['text'] >= cost:
self.buy['state'] = 'normal'
else:
self.buy['state'] = 'disabled'
self.number['text'] >= cost
self.progress['value'] = one
if self.number['text'] >= cost:
self.progress['style'] = 'red.Vertical.TProgressbar'
else:
self.progress['style'] = 'green.Vertical.TProgressbar'
def Buy(self):
global one
self.w['to'] += 1
cost = 10*(self.w['to'])
one = self.number['text'] = (one + 10 - cost)
self.buy['text'] = ('+1 to slider | Cost: {}'.format(cost))
if self.number['text'] < (cost):
self.buy['state'] = 'disabled'
self.progress['value'] = one
self.progress['maximum'] += 10
if self.number['text'] >= cost:
self.progress['style'] = 'red.Vertical.TProgressbar'
else:
self.progress['style'] = 'green.Vertical.TProgressbar'
def scaleValue(self, event):
self.v['text'] = 'Slider Bonus + ' + str(iround(self.w.get()))
def clicks(self, event):
global click
global clack
if self.Clicks['text'] == 'Clicks: 0':
clack += 1
self.Clicks['text'] = click.format(clack)
self.Clicks['text'] = click.format(clack)
clack += 1
def NumberVal(self, event):
global why
global no
if self.fun['text'] == "Total Number: 0":
self.fun['text'] = why.format(no)
if iround(self.w.get()) == 0:
no += 1
else:
no += iround(self.w.get())
self.fun['text'] = why.format(no)
def createWidgets(self):
self.number = Button(self, text = 'Make number go up', command = self.Number, width = 20, style = 'TButton')
self.number.grid(row = 1, column = 1)
self.number.bind('<ButtonRelease>', self.clicks, add = '+')
self.number.bind('<ButtonRelease>', self.NumberVal, add = '+')
self.buy = Button(self, text = '+1 to Slider | Cost: 10', command = self.Buy, width = 20, style = 'TButton')
self.buy.grid(row = 2, column = 1)
self.buy.config(state = 'disabled')
self.v = Label(self, text = 'Slider Bonus + 0', width = 20, anchor = 'center')
self.v.grid(row = 3, column = 3)
self.w = Scale(self, from_ = 0, to = 1, orient = 'horizontal')
self.w.grid(row = 3, column = 1)
self.w.bind('<Motion>', self.scaleValue)
self.progress = Progressbar(self, value = 0, orient = 'vertical', maximum = 10, mode = 'determinate')
self.progress.grid(row = 1, rowspan = 5, column = 2)
self.Clicks = Label(self, text = 'Clicks: 0', width = 20, anchor = 'center')
self.Clicks.grid(row = 1, column = 3)
self.fun = Label(self, text = 'Total Number: 0', width = 20, anchor = 'center')
self.fun.grid(row = 2, column = 3)
app = Application()
app.master.title('Number')
app.mainloop()
I need to know how to implement the selected radio button into my calculations. Thanks for any and all help! I'm really not positive what the problem is, my only quest really comes from the "def selection" part. I just don't know what to do there
from Tkinter import *
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.headerFont = ("Times", "16", "italic")
self.title("Restaurant Tipper")
self.addOrigBill()
self.addChooseOne()
self.addPercTip()
self.addRateTip()
self.addOutput()
def addOrigBill(self):
Label(self, text = "Bill Amount",
font = self.headerFont).grid(columnspan = 1)
self.txtBillAmount = Entry(self)
self.txtBillAmount.grid(row = 1, column = 1)
self.txtBillAmount.insert(0,"100.00")
def addChooseOne(self):
Label(self, text = "Pick ONE! Choose your % of Tip or Rate your experience",
font = self.headerFont).grid(row = 2, column = 1)
def addPercTip(self):
Label(self, text = "% of Tip",
font = self.headerFont).grid(row = 3, column = 0)
self.radPercTip1 = Radiobutton(self, text = "15%",
variable = self.percVar, value = .15, command = self.selected)
self.radPercTip2 = Radiobutton(self, text = "17%",
variable = self.percVar, value = .17, command = self.selected)
self.radPercTip3 = Radiobutton(self, text = "20%",
variable = self.percVar, value = .20, command = self.selected)
self.radPercTip1.grid(row = 4, column = 0)
self.radPercTip2.grid(row = 5, column = 0)
self.radPercTip3.grid(row = 6, column = 0)
def selected(self):
float(self.percVar.get())
def addRateTip(self):
Label(self, text = "Tip by rating").grid(row = 3, column = 3)
Label(self, text = "1 being the worst").grid(row = 4, column = 3)
Label(self, text = "10 being the best").grid(row = 5, column = 3)
Label(self, text = "Experience").grid(row = 6, column = 2)
self.txtExperience = Entry(self)
self.txtExperience.grid(row = 6, column = 3)
def addOutput(self):
self.btnCalc = Button(self, text = "Calculate Tip")
self.btnCalc.grid(row = 7, columnspan = 2)
self.btnCalc["command"] = self.calculate
Label(self, text = "Tip").grid(row = 8, column = 1)
self.lblTip = Label(self, bg = "#ffffff", anchor = "w", relief = "ridge")
self.lblTip.grid(row = 8, column = 2, sticky = "we")
Label(self, text = "Total Bill").grid(row = 9, column = 1)
self.lblTotalBill = Label(self, bg = "#ffffff", anchor = "w", relief = "ridge")
self.lblTotalBill.grid(row = 9, column = 2, sticky = "we")
def calculate(self):
bill = float(self.txtBillAmount.get())
percTip = self.percVar
rateTip = int(self.addRateTip.get())
tip = bill * percTip
self.lblTip["text"] = "%.2f" % tip
totalBill = tip + bill
self.lblTotalBill["text"] = "%.2f" % totalBill
if rateTip <= 2:
percTip = .10
elif 3 <= rateTip <= 4:
percTip = .12
elif 5 <= rateTip <= 6:
percTip = .15
elif 7 <= rateTip <= 8:
percTip = .17
elif 9 <= rateTip <= 10:
percTip = .20
else:
self.lblTotalBill["text"] = "Something is wrong"
def main():
app = App()
app.mainloop()
if __name__ == "__main__":
main()
There is no self.percVar in your code. As #wastl said, you need to initialize it.
To do that, you need to use one of the variable classes. Since you are using float type, DoubleVar() would be the best.
def addPercTip(self):
self.percVar = DoubleVar() #this line should be added in your method
Label(self, text = "% of Tip",
font = self.headerFont).grid(row = 3, column = 0)
def selected(self):
print (type(self.percVar.get()))
#which is float, without converting explicitly because of DoubleVar()
print (self.percVar.get())
#this will print what you click
You forgot to intialize the self.percVar variable
Add self.percVar = 0 as the first line of the addPercTip method. That should fix your error.
BTW: For future questions the best thing is to include the error message you get and EXACTLY describe what part of the programm causes what kind of trouble for you