Counting the number of times button is clicked during my program - python

I am doing a program on a class list counter. I have one program, in frame 5 underneath "Population Count" and where it says 0, it is meant to increase by one for every time the button "Add to classlist" is clicked every time. I tried many different methods but all of those I tried never seem to work. It would be appreciative if anyone can help.
Here is my coding so far, the rest I have done for my class list counter
import pickle
import os.path
from tkinter import *
import tkinter.messagebox
import tkinter as tk
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation():
def __init__(self):
window = Tk()
window.title("Class population")
self.firstnameVar = StringVar()
self.lastnameVar = StringVar()
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "First name").grid(row = 1,
column = 1, sticky = W)
Entry(frame1, textvariable = self.firstnameVar,
width = 40).grid(row = 1, column = 2)
frame2 = Frame(window)
frame2.pack()
Label(frame2, text = "Last name").grid(row = 1, column = 1, sticky = W)
Entry(frame2, textvariable = self.lastnameVar,
width = 40).grid(row = 1, column = 2)
frame3 = Frame(window)
frame3.pack()
Button(frame3, text = "Add to classlist",
command = self.processAdd).grid(row = 1, column = 1)
frame4 = Frame(window)
frame4.pack()
Label(frame4, text = "Population Count").grid(row = 1, column = 1, sticky = W)
frame5 = Frame(window)
frame5.pack()
Label(frame5, text = "0").grid(row = 1, column = 1, sticky = W)
population = 0
def population(label):
population = 0
def mbutton():
global population
population +=1
label.config(text=str(population))
self.classList = self.loadClass()
self.current = 0
if len(self.classList) > 0:
self.setClass()
def saveClass(self):
outfile = open("Population.dat", "wb")
pickle.dump(self.classList, outfile)
tkinter.messagebox.showinfo("Class Population","New name registered")
outfile.close()
def loadClass(self):
if not os.path.isfile("Population.dat"):
return [] # Return an empty list
try:
infile = open("Population.dat", "rb")
classList = pickle.load(infile)
except EOFError:
classList = []
infile.close()
return classList
def processAdd(self):
classList = Class(self.firstnameVar.get(), self.lastnameVar.get())
self.classList.append(classList)
self.saveClass()
def setClass(self):
self.firstnameVar.set(self.classList[self.current].firstname)
self.lastnameVar.set(self.classList[self.current].lastname)
ClassPopulation()

Rather than using a global population you need to declare self.population = 0 in your __init__ method and to increment self.population in your button click handler. It is normally also considered good practice to have a class method to get the value.

Possible solution: if all you want to do is, have the population count, and increment it on each button click:
import pickle
import os.path
from tkinter import *
import tkinter.messagebox
import tkinter as tk
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation():
def __init__(self):
window = Tk()
window.title("Class population")
self.firstnameVar = StringVar()
self.lastnameVar = StringVar()
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "First name").grid(row = 1,
column = 1, sticky = W)
Entry(frame1, textvariable = self.firstnameVar,
width = 40).grid(row = 1, column = 2)
frame2 = Frame(window)
frame2.pack()
Label(frame2, text = "Last name").grid(row = 1, column = 1, sticky = W)
Entry(frame2, textvariable = self.lastnameVar,
width = 40).grid(row = 1, column = 2)
frame3 = Frame(window)
frame3.pack()
Button(frame3, text = "Add to classlist",
command = self.processAdd).grid(row = 1, column = 1)
frame4 = Frame(window)
frame4.pack()
Label(frame4, text = "Population Count").grid(row = 1, column = 1, sticky = W)
frame5 = Frame(window)
frame5.pack()
Label(frame5, text = "0").grid(row = 1, column = 1, sticky = W)
# population = 0
self.population = 0 # made it a class attr
# def population(label):
# population = 0
def add_population(self):
# having it separate can help in modification or enhancement
self.population +=1
def mbutton():
# global population
# population +=1
self.add_population() # increment
label.config(text=str(population))
self.classList = self.loadClass()
self.current = 0
if len(self.classList) > 0:
self.setClass()
def saveClass(self):
outfile = open("Population.dat", "wb")
pickle.dump(self.classList, outfile)
tkinter.messagebox.showinfo("Class Population","New name registered")
outfile.close()
def loadClass(self):
if not os.path.isfile("Population.dat"):
return [] # Return an empty list
try:
infile = open("Population.dat", "rb")
classList = pickle.load(infile)
except EOFError:
classList = []
infile.close()
return classList
def processAdd(self):
classList = Class(self.firstnameVar.get(), self.lastnameVar.get())
self.classList.append(classList)
self.saveClass()
def setClass(self):
self.firstnameVar.set(self.classList[self.current].firstname)
self.lastnameVar.set(self.classList[self.current].lastname)
ClassPopulation()
Edit 1: I have added the complete code, with my suggested changes - previous statements are commented, so you know the changes.

Related

creating button with tkinter

I was really curious why I cannot get my add_button to work,
as the window fails to come up when creating it.
from tkinter import *
class Calculator:
#-------------------------------------------------
def __init__(self, master):
self.master = master
master.title("Calculator")
self.close_button = Button(master, text = "Close", command = master.destroy)
Label(master, text = "First Digit").grid(row = 0)
Label(master, text = "Second Digit").grid(row = 1)
self.input1 = 0
self.input2 = 0
input1 = Entry(master)
input2 = Entry(master)
input1.grid(row = 0, column = 1)
input2.grid(row = 1, column = 1)
self.close_button.grid(row = 2, column = 0)
self.add_buton = Button(master, text = "Add", command = self.add())
self.add_button.grid(row = 2, column = 1)
master.configure(background = 'grey')
return
#-------------------------------------------------
def add(self):
return self.input1.get() + self.input2.get()
#-------------------------------------------------
#-------------------------------------------------
root = Tk()
calc = Calculator(root)
root.mainloop()
#-------------------------------------------------
Welcome to Stack!
I've looked through you code I've been able to do what you are asking. There were a few errors within your code:
a) you had self.add_buton and self.add_button which caused an error.
b) self.input1 = 0 and self.input2 = 0 are not required.
c) You were calling self.add() as the command and you should be calling self.add. When calling it as a command you do not need ()
d)input1 = Entry(master) should be self.input1 = tk.Entry(master)
e) You should convert your input values into int or float as otherwise it will just one value onto the end of the other. (Eg, 1 + 5 = 15 whereas int(1) + int(5) = 6
Here is your code with the entry boxes working as they should. I have import tkinter as tk hence why it is tk.Entry
from tkinter import *
import tkinter as tk
class Calculator:
#-------------------------------------------------
def __init__(self, master):
self.master = master
master.title("Calculator")
self.close_button = Button(master, text = "Close", command = master.destroy)
Label(master, text = "First Digit").grid(row = 0)
Label(master, text = "Second Digit").grid(row = 1)
self.input1 = tk.Entry(bd=5, width=35, background='gray35', foreground='snow')
self.input2 = tk.Entry(bd=5, width=35, background='gray35', foreground='snow')
self.input1.grid(row = 0, column = 1)
self.input2.grid(row = 1, column = 1)
self.close_button.grid(row = 2, column = 0)
self.add_button = tk.Button(master, text = "Add", command = self.add)
self.add_button.grid(row = 2, column = 1)
master.configure(background = 'grey')
return
#-------------------------------------------------
def add(self):
val = self.input1.get()
print(val)
#-------------------------------------------------
#-------------------------------------------------
root = Tk()
calc = Calculator(root)
root.mainloop()
This should now work how you wanted it too. The variables within the entry can be changed to suit. You were correct in calling the value of the entry with self.input1.get().
Hope this has helped.

Class Population Counter. How to put the program all into one

I am trying to develop a class population counter. The problem is that when I run it 2 program come up. I wanted my program to be all in one. The counter keeps coming in a separate program and i can't transfer it into my actual program. How do I do this?
Here is my attached files, I am using Python
import pickle
import os.path
from tkinter import *
import tkinter.messagebox
import tkinter as tk
population = 0
def counter_label(label):
population = 0
def count():
global population
population +=1
label.config(text=str(population))
root = tk.Tk()
label = tk.Label(root)
label.pack()
counter_label(label)
button = tk.Button(root, text='Population Count', command=count).pack()
root.mainloop()
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation:
def __init__(self):
window = Tk()
window.title("Class population")
self.firstnameVar = StringVar()
self.lastnameVar = StringVar()
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "First name").grid(row = 1,
column = 1, sticky = W)
Entry(frame1, textvariable = self.firstnameVar,
width = 40).grid(row = 1, column = 2)
frame2 = Frame(window)
frame2.pack()
Label(frame2, text = "Last name").grid(row = 1, column = 1, sticky = W)
Entry(frame2, textvariable = self.lastnameVar,
width = 40).grid(row = 1, column = 2)
frame3 = Frame(window)
frame3.pack()
Button(frame3, text = "Add to classlist",
command = self.processAdd).grid(row = 1, column = 1)
frame4 = Frame(window)
frame4.pack()
Label(frame4, text = "Population Count").grid(row = 1, column = 1, sticky = W)
frame5 = Frame(window)
frame5.pack()
Label(frame5, text = "0").grid(row = 1, column = 1, sticky = W)
self.classList = self.loadClass()
self.current = 0
if len(self.classList) > 0:
self.setClass()
def saveClass(self):
outfile = open("Population.dat", "wb")
pickle.dump(self.classList, outfile)
tkinter.messagebox.showinfo("Class Population","New name registered")
outfile.close()
def loadClass(self):
if not os.path.isfile("Population.dat"):
return [] # Return an empty list
try:
infile = open("Population.dat", "rb")
classList = pickle.load(infile)
except EOFError:
classList = []
infile.close()
return classList
def processAdd(self):
classList = Class(self.firstnameVar.get(), self.lastnameVar.get())
self.classList.append(classList)
self.saveClass()
def setClass(self):
self.firstnameVar.set(self.classList[self.current].firstname)
self.lastnameVar.set(self.classList[self.current].lastname)
ClassPopulation()
I think two windows are coming up is because the program runs Tk() twice - one root = tk.Tk() and another in window = Tk(). If you pass your root Tkinter instance to the class ClassPopulation, then it should show one single window.
[EDIT]
class Class:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
class ClassPopulation:
def __init__(self, root_window):
window = self.root_window
window.title("Class population")
population = 0
def counter_label(label):
population = 0
def count():
global population
population +=1
label.config(text=str(population))
root = Tk()
label = tk.Label(root)
label.pack()
ClassPopulation( root )
counter_label(label)
root.mainloop()

Python Tkinter. How to store entry via button in label

I really need help with some code. I don't expect you to write it for me, since it is a school project, but I am just really lost and need help.
The code I am writing is some sort of production system.
It doesn't need to actually be able to send a task anywhere, since this is just an imagined scenario.
The code has to consist of three files: data.py, model.py and gui.py.
Gui can access the two other files
Data can only access model
Model can't access either of the other two.
My teacher had written some of the code witch I have continued on. Some of the text is in danish, but most comments are in English.
The code is as follows.
data.py
from model import *
class Data(object):
def __init__(self):
self.units = []
self.finished_tasks = []
def __str__(self):
result = "These tasks have been finished: "
for i in self.finished_tasks:
result += str(i)
return result
def task_done(self, unit):
done_task = unit.task_done()
if done_task != None:
#TODO: add to list of finished tasks
pass
def add_task(self, name, amount, unit):
s = Springroll_task(name, amount)
unit.add_to_queue(s)
def read_from_database(self):#doesn't actually read from db..
self.units.append(Production_unit("maskine1"))
self.units.append(Production_unit("maskine2"))
self.add_task("Miniruller", 100, self.units[0])
self.add_task("Maxiruller", 200, self.units[0])
self.add_task("HowIRoll", 3000, self.units[0])
self.add_task("RulleMarie", 40, self.units[1])
self.add_task("Rullesten", 500, self.units[1])
self.add_task("Toiletpapirsruller", 6000, self.units[1])
model.py
class Springroll_task(object):
def __init__(self, name, amount):
self.name = name
self.amount = amount
def __str__(self):
return self.name + " " + str(self.amount)
class Production_unit(object):
def __init__(self, amount={}, name={},):
#name of the production unit
self.name = name
self.amount = amount
#the current task
self.current_task = None
#the tasks in the queue
self.springroll_queue = []
#the size of the queue
self.queue_size = 0
def __str__(self):
#TODO
return self.name + " " + str(self.amount)
def add_to_queue(self, task={}):
if self.current_task == None:
self.current_task = task
else:
self.springroll_queue.append(task)
self.queue_size += 1
#remember to update queue_size
pass
def task_done(self):
#TODO: remember the old current task.
#Set the current task to be the first in the queue (and remove from queue)
# - if there is a task in the queue.
#return the old current task.
#remember to update queue_size
self.queue_size -= 1
pass
gui.py
from tkinter import *
from model import *
from data import Data
class Application(Frame):
def __init__(self, master, unit):
self.mod = Production_unit()
super(Application, self).__init__(master)
self.grid()
self.unit = unit
self.create_widgets()
def create_widgets(self):
self.unit_name_lbl = Label(self, text = self.unit.name)
self.unit_name_lbl.grid(row = 0, column = 0, columnspan = 2, sticky = W)
self.cur_prod_lbl = Label(self, text = "produktion nu: ")
self.cur_prod_lbl.grid(row = 1, column = 0, columnspan = 2, sticky = W)
self.prod_lbl = Label(self, text = "produkt")
self.prod_lbl.grid(row = 2, column = 0, sticky = W)
self.amount_lbl = Label(self, text = "antal")
self.amount_lbl.grid(row = 2, column = 1, sticky = W)
#Label for production now
self.amount1_lbl = Label(self, text = " ", bg ="red")
self.amount1_lbl.grid(row = 3, column = 0, sticky = W)
self.amount2_lbl = Label(self, text = " ", bg ="red")
self.amount2_lbl.grid(row = 3, column = 1, sticky = W)
#Button for task finished
self.finished_but = Button(self, text = "Opgave afsluttet", bg ="pink", command=self.mod.task_done)
self.finished_but.grid(row = 3, column = 2, sticky = W)
#Label for queue
self.queue_lbl = Label(self, text = "Kø")
self.queue_lbl.grid(row = 4, column = 0, sticky = W)
#Label for production queue
for i in range(0,3):
self.name_lbl =Label(self, text = self.mod.springroll_queue, bg="red", width= 6)
self.name_lbl.grid(row = 5+i, sticky = W)
for j in range(0,3):
self.qt_lbl =Label(self, text = self.mod.springroll_queue, bg="red", width= 4)
self.qt_lbl.grid(row = 5+j, column = 1)
self.new_lbl = Label(self, text = "Ny")
self.new_lbl.grid(row = 10, column = 0, sticky = W)
#Entry for entries
self.eq1_ent = Entry(self, text = "", width=6)
self.entry_name = self.eq1_ent.get()
self.eq1_ent.grid(row = 11, sticky = W)
self.ea1_ent = Entry(self, text = "", width=4)
self.ea1_ent.grid(row = 11, column = 1, sticky = W)
#Button for add to queue
self.add_but = Button(self, text = "Tilføj til kø", bg ="pink", command=self.mod.add_to_queue(self.ea1_ent.get()))
self.add_but.grid(row = 11, column = 2, sticky = W)
def done(self):
d.task_done(self.unit)
self.redraw()
def add(self):
n = "Nyt navn" #read from gui
a = "Nyt antal" #read from gui
d.add_task(n, a, unit)
self.redraw()
def redraw(self):
#TODO
pass
# main
root = Tk()
root.title("Daloon")
root.geometry("300x300")
d = Data()
d.read_from_database()
p = d.units[0]
app = Application(root, p)
root.mainloop()
So it currently looks like this:
What I need to be able to do is to take an input in the bottom two entry widgets and put them in one of the 4 label widgets above, beginning from the top and then in the queue afterwards, this should happen when I press the button add_but, which seems to be gone currently.
After that I need the task stored in the data file when the "Opgave afsluttet" button is pressed.
I really hope someone is able to help me!
I edited it with some suggestions, and am calling the right self.eq1_ent.get() now, I think. I dont get any error any longer, now I just don't really know how to make it do what I want.
Edit 2: I am slowly getting some stuff, so i have made changes in the model.py and gui.py...
It looks like this now:
self.eq1 is not defined. you have self.q1_lbl and self.eq1_ent.
To access the label use self.q1_lbl.
To be able to set text to your label create them as following:
self.var = StringVar()
self.unit_name_lbl = Label(self, textvariable=self.var)
For example, from redraw() you can set 'text' to self.unit_name_lbl like this : self.var.set('text').
Check if you missed self in d.add_task(n, a, unit)
When you do command=mod.add_to_queue(self.ea1_ent.get()) the mod.add_to_queue function will be called directly, if you want to pass argument to this function when user press the button, you can use lambda:
command=lambda: mod.add_to_queue(self.ea1_ent.get)

Refering to Labels Python, Tkinter

I'd like to refer to labels in def check(self) . It should check if feedback from external device equals to something, but I don't know how to refer to label and change colour of it if it's equal or not. I'd like to change for example lab3 background to green or red, depending on equality. Here is my code:
# -*- coding: utf-8 -*-
import Tkinter as T, tkFileDialog
import os
from time import *
import serial
from ttk import Button, Label, Frame, Entry, Style
class Program(Frame):
def __init__(self, root):
Frame.__init__(self, root)
self.root = root
self.initUI()
def initUI(self):
self.root.title('OptoMaQ')
Style().configure('TFrame', background = '#6666ff')
Style().configure('TButton',background = '#6666ff')
lab1 = Label(self, text = 'Press Save to save a file', background = '#6666ff').grid(row = 0, columnspan = 5)
but1 = Button(self, text='Save', command=self.save).grid(row = 2,column = 1)
lab2 = Label(self, text = 'Press Exit to quite', background = '#6666ff').grid(row = 1, columnspan = 5)
but2 = Button(self, text = 'Exit',command = self.exit).grid(row = 2, column = 2)
lab3 = Label(self, text = 'Spectra-Hub', background = '#6666ff').grid(row = 3, columnspan = 5)
lab4 = Label(self, text = 'SpectraPro VM-504',background = '#6666ff').grid(row = 4,columnspan = 5)
lab5 = Label(self, text = 'SpectraPro SP-2-300i',background = '#6666ff').grid(row = 5, columnspan = 5)
but3 = Button(self, text = 'Check',command = self.check).grid(row = 6, columnspan = 5)
lab6 = Label(self, text = 'Type sth here', background = '#6666ff').grid(row = 7,columnspan = 5)
self.entry = Entry(self, justify = 'center',text = '1')
self.entry.grid(row = 8, columnspan =3)
self.fileop = options = {}
options['filetypes'] = [('all files', '.*'),('dat files','.dat'),('text files', '.txt')]
options['initialfile'] = 'file.txt'
options['parent'] = root
def check(self):
port = serial.Serial(15)
command = 'WHO'
port.write(command + '\r')
out = port.read(50)
if out == 'Acton Research Corp. \nSpectra-Hub':
lab3 = Label(self, text = 'Spectra-Hub', background = '#6666ff').grid(row = 3, columnspan = 5)
lab3.config(background = 'green')
port.close()
else:
lab3 = Label(self, text = 'Spectra-Hub', background = '#6666ff').grid(row = 3, columnspan = 5)
lab3.config(background = 'red')
port.close()
port2 = serial.Serial(16)
port2.write(command +'\r')
out2 = port2.read(50)
if out2 == 'Acton Research Corp. \nSpectraPro VM-504':
port2.close()
else:
port2.close()
port3 = serial.Serial(17)
port3.write(command + '\r')
out3 = port3.read(46)
if out3 == 'Acton Research Corp. \n SpectraPro SP-2-300i':
port3.close()
else:
port3.close()
def save(self):
filename = tkFileDialog.asksaveasfilename(**self.fileop)
if filename:
file = open(filename, 'a+')
time = strftime("%A, %d %b %Y, %H:%M:%S ", gmtime())
print time
file.write(time)
file.write('\n')
input = str(self.entry.get())
file.write(input)
file.close()
def exit(self):
root.destroy()
if __name__=='__main__':
root = T.Tk()
Program(root).pack()
root.mainloop()
I've tried something like this in lines 46-53 but it doesn't work. It shows that 'NoneType' object has no attribute 'config' in line 52. Any ideas? It's really important to me please help :)
That is because your labels are only defined in the scope of def initUI(self): and therefore inaccessible to def check(self)
Try defining your buttons as self.lab1 instead of lab1 and also refer to them in the same way.

TKinter process is not drawing Labels, Buttons, and Entry Fields... What am I doing wrong?

I'm a full time student, taking my first class in python.
This is so strange, it was working, and now, it is no longer showing the buttons, labels, and entry fields. I'm sure it was something I removed or added, but, I'm at a loss.
Any ideas? All suggestions are appreciated.
from Tkinter import *
import tkFont
import tkMessageBox
class BouncyGUI(Frame):
"""The GUI used to interface with the bouncy calculation from chapter 9 section 1."""
def __init__(self):
Frame.__init__(self)
# Establish the Base Frame
self.master.title("Calculate the Bounciness of a Ball")
self.master.rowconfigure(0, weight = 1)
self.master.columnconfigure(0, weight = 1)
self.master.grid()
self.master.resizable(0,0)
# Establish the components for capturing the Height
self._heightLabel = Label(self,
text = "Height of initial drop:",
justify = "left")
self._heightLabel.grid(row = 0, column = 0)
self._heightVar = DoubleVar()
self._heightEntry = Entry(self,
textvariable = self._heightVar,
justify = "center")
self._heightEntry.grid(row = 0, column = 1)
# Establish the "bounciness index"
self._bouncyIndex = Label(self,
text = "Bounciness Index:",
justify = "left")
self._bouncyIndex.grid(row = 1, column = 0)
self._bouncyVar = DoubleVar()
self._bouncyEntry = Entry(self,
textvariable = self._bouncyVar,
justify = "center")
self._bouncyEntry.grid(row = 1, column = 1)
self._bouncyVar.set(0.6)
# Establish number of allowable bounces
self._numberBounces = Label(self,
text = "Number of Bounces:",
justify = "left")
self._numberBounces.grid(row = 2, column = 0)
self._numberBouncesVar = IntVar()
self._numberBouncesEntry = Entry(self,
textvariable = self._numberBouncesVar,
justify = "center")
self._numberBouncesEntry.grid(row = 2, column = 1)
# Establish a field for the response
self._answer = Label(self,
text = "Distance Travelled",
justify = "left")
self._answer.grid(row = 3, column = 0)
self._answerVar = DoubleVar()
self._answerFont = tkFont.Font(weight="bold", size = 12)
self._answerEntry = Entry(self,
textvariable = self._answerVar,
justify = "center",
font = self._answerFont)
self._answerEntry.grid(row = 3, column = 1)
self._answerEntry.config(state = DISABLED, bg = "green")
# Create frame to hold buttons
self._buttonFrame = Frame(self)
self._buttonFrame.grid(row = 4, column = 0, columnspan = 2)
# Create Reset Button
self._buttonReset = Button(self._buttonFrame,
text = "Reset",
command = self._reset,
width = 15,
padx = 2,
pady = 2)
self._buttonReset.grid(row = 0, column = 0)
#self._buttonReset.config(state = DISABLED)
# Create Calculate Button
self._buttonCalc = Button(self._buttonFrame,
text = "Calculate",
command = self._calculate,
width = 15,
padx = 2,
pady = 2)
self._buttonCalc.grid(row = 0, column = 1)
#self._buttonCalc.config(state = NORMAL)
def _reset(self):
"""Allow for the screen to reset for fresh data entry."""
self._heightVar.set(0.0)
self._numberBouncesVar.set(0)
self._answerVar.set(0.0)
#self._buttonCalc.config(state = NORMAL)
#self._buttonReset.config(state = DISABLED)
#self._numberBouncesEntry.config(state = NORMAL)
#self._bouncyEntry.config(state = NORMAL)
#self._heightEntry.config(state = NORMAL)
def _calculate(self):
"""Calculate the bounciness and update the GUI"""
if self._validDataTypes():
self._answerVar.set(computeDistance(self._heightVar.get(), \
self._bouncyVar.get(), \
self._numberBouncesVar.get()))
#self._numberBouncesEntry.config(state = DISABLED)
#self._bouncyEntry.config(state = DISABLED)
#self._heightEntry.config(state = DISABLED)
#self._buttonCalc.config(state = DISABLED)
#self._buttonReset.config(state = NORMAL)
def _validDataTypes(self):
theMessage = ""
if self._isInt(self._numberBouncesVar.get()) != True:
theMessage += "Please re-enter Integer Value for Number of Bounces.\n"
elif self._isFloat(self._bouncyVar.get()) != True:
theMessage += "Please re-enter Float Value for Bounciness Index.\n"
elif self._isFloat(self._heightVar.get()) != True:
theMessage += "Please re-enter Float Value for Initial Height."
if len(message) > 0:
tkMessageBox.showerror(message = message, parent = self)
return False
else:
return True
def _isInt(self, value):
# Test to ensure that value entered is an integer
try:
x = int(value)
except ValueError:
# If not return false
return False
# if it is an integer, return true
return True
def _isFloat(self, value):
# Test to ensure that value entered is a float value
try:
x = float(value)
except ValueError:
# If not return false
return False
# If it is a float, return true
return True
def computeDistance(height, index, bounces):
"""Compute the distance travelled."""
total = 0
for x in range(bounces):
total += height
height *= index
total += height
return total
def main():
"""Run the main program"""
BouncyGUI().mainloop()
main()
Your main() function setup code isn't working properly. I'm not sure how you had it set up before, but one way to get it working is this:
def main():
"""Run the main program"""
root = Tk()
gui = BouncyGUI()
gui.pack()
root.mainloop()
You need to grid the main app, not just call its mainloop:
def main()
app = BouncyGUI()
app.grid()
app.mainloop()
there is an error in your code when compiling:
NameError: global name 'message' is not defined

Categories