Getting Input from Radiobutton - python

I am using a mix of Tkinter and graphics.py (a wrapper on Tkinter) to create a fairly basic integrator (find the area under a graph) with a GUI. As of now, the main "control panel" for the integrator is separate from the actual graph (which is made by using graphics.py). I am using Tkinter's Radiobutton() for the choice selection of the integration type (Left Rectangular, Right Rectangular, Trapezoidal, or Simpson's Approximation).
My problem is that I am unable to get the output from the radiobuttons. I was using the example from TutorialsPoint: Tkinter Radiobutton.
Here is my code:
class FunctionInput:
def __init__(self, master, window, items):
self.window = window
self.items = items
self.runProgram = True
self.typeChoice = tk.StringVar()
self.frame = tk.Frame(master)
self.typeFrame = tk.Frame(self.frame)
self.quitButton = tk.Button(self.frame, text = 'Quit', command = self.frame.quit)
self.optLabel = tk.Label(self.frame, text = 'Type of Approximation: ')
self.optL = tk.Radiobutton(self.typeFrame, text = 'Left Rectangular', variable = self.typeChoice, value = 'l')
self.optR = tk.Radiobutton(self.typeFrame, text = 'Right Rectangular', variable = self.typeChoice, value = 'r')
self.optT = tk.Radiobutton(self.typeFrame, text = 'Trapezoidal', variable = self.typeChoice, value = 't')
self.optS = tk.Radiobutton(self.typeFrame, text = 'Simpsons Rule', variable = self.typeChoice, value = 's')
self.optL.grid(row = 1, column = 1, padx = 5, pady = 5)
self.optR.grid(row = 1, column = 2, padx = 5, pady = 5)
self.optT.grid(row = 2, column = 1, padx = 5, pady = 5)
self.optS.grid(row = 2, column = 2, padx = 5, pady = 5)
self.optLabel.grid(row = 4)
self.typeFrame.grid(row = 5)
self.quitButton.grid(row = 6)
# there were numerous other widgets and frames, but I only included the relevant ones
self.frame.grid()
def getInput(self):
type_integration = self.typeChoice.get()
self.frame.quit()
return type_integration
def main():
# some other code, win and axisLabels are defined prior to this
root = tk.Tk(className = ' Function Grapher')
app = FunctionInput(root, win, axisLabels)
root.rowconfigure(0, weight = 1)
root.columnconfigure(0, weight = 1)
root.mainloop() # there is a button to exit the mainloop in my GUI
typeIntegration = app.getInput()
print typeIntegration # trying to debug it
if __name__ == '__main__': main()
However, it doesn't not print the variable. It prints an empty string, so execution is not a problem. root.mainloop() does not get stuck in an infinite loop, because I have a button in my GUI (not shown here because it is irrelevant) that exits it. An error is not raised, so I'm guessing that the issue is with setting the option to the variable. Any help is greatly appreciated.
Also, on a side note, whenever I run the program, the 'Right Rectangular', 'Trapezoidal', and 'Simpson's Rule' radiobuttons are grayed out, like such:
This grayness goes away if I click on one of the radiobuttons, but until then, it stays. If there is some way to fix this, please let me know.
Thanks!

I haven't seen the part of the exit button, but your code does something like this:
Starts the mainloop
The event handler of the exit button calls root.quit()
In getInput, retrieves the value and calls self.frame.quit()
Calling Tkinter functions after the mainloop may lead to problems like this, so you should get the value of the StringVar first and then exit the GUI loop. This is a working example based on your code:
import Tkinter as tk
class App():
def __init__(self, master):
self.master = master
self.type_integration = None
self.typeChoice = tk.StringVar()
self.typeChoice.set(None) # This fixes the grayness of the radio buttons!
self.typeFrame = tk.Frame(master)
OPTIONS = [('Left Rectangular', 'l'),
('Right Rectangular', 'r'),
('Trapezoidal', 't'),
('Simpsons Rule', 's')]
for text, value in OPTIONS:
tk.Radiobutton(self.typeFrame, text=text, variable=self.typeChoice, value=value).pack()
tk.Button(self.typeFrame, text="Exit", command=self.exit).pack()
self.typeFrame.pack()
def exit(self):
self.type_integration = self.typeChoice.get()
self.master.destroy() # self.master.quit() freezes the GUI
def getinput(self):
return self.type_integration
master = tk.Tk()
app = App(master)
tk.mainloop()
print app.getinput()

The problem was that since I was using multiple other widgets, I had to set StringVar()s master parameter as self.typeFrame:
class FunctionInput:
def __init__(self, master, window, items):
self.window = window
self.items = items
self.runProgram = True
self.frame = tk.Frame(master)
self.typeFrame = tk.Frame(self.frame)
self.typeChoice = tk.StringVar(self.typeFrame)
self.quitButton = tk.Button(self.frame, text = 'Quit', command = self.frame.quit)
self.optLabel = tk.Label(self.frame, text = 'Type of Approximation: ')
self.optL = tk.Radiobutton(self.typeFrame, text = 'Left Rectangular', variable = self.typeChoice, value = 'l')
self.optR = tk.Radiobutton(self.typeFrame, text = 'Right Rectangular', variable = self.typeChoice, value = 'r')
self.optT = tk.Radiobutton(self.typeFrame, text = 'Trapezoidal', variable = self.typeChoice, value = 't')
self.optS = tk.Radiobutton(self.typeFrame, text = 'Simpsons Rule', variable = self.typeChoice, value = 's')
self.optL.grid(row = 1, column = 1, padx = 5, pady = 5)
self.optR.grid(row = 1, column = 2, padx = 5, pady = 5)
self.optT.grid(row = 2, column = 1, padx = 5, pady = 5)
self.optS.grid(row = 2, column = 2, padx = 5, pady = 5)
self.optLabel.grid(row = 4)
self.typeFrame.grid(row = 5)
self.quitButton.grid(row = 6)
# there were numerous other widgets and frames, but I only included the relevant ones
self.frame.grid()
def getInput(self):
type_integration = self.typeChoice.get()
self.frame.quit()
return type_integration
def main():
# some other code, win and axisLabels are defined prior to this
root = tk.Tk(className = ' Function Grapher')
app = FunctionInput(root, win, axisLabels)
root.rowconfigure(0, weight = 1)
root.columnconfigure(0, weight = 1)
root.mainloop() # there is a button to exit the mainloop in my GUI
print app.getInput()
if __name__ == '__main__': main()
Also, as #A. Rodas said, to get rid of the grayness, I did:
self.typeFrame = tk.Frame(self.frame)
self.typeChoice = tk.StringVar(self.typeFrame)
self.typeChoice.set(None)

Related

Need to get the multi-digit integer Entry value after the last digit key is pressed

I am relatively new to tkinter, and very new to coding with classes. My GUI will have a step that asks user to enter in an integer with any number of digits to an Entry(). After the last digit keypress (no keypress in 2000 ms) another function will activate that uses the integer entered. It seems very simple but I cannot seem to get this right. I haven't figured out the .after() part, for now I am just using a binding on the ENTER key. Details on the problems, then the code below. I feel like I am struggling way too much on something that can't be that difficult. Please help.
(Some?) Details:
I am getting a bunch of errors leading up to entry input, regarding 'val' not being defined, despite it being defined.
Pressing ENTER does not result in any return value (I added a print command to the mouse clicks just to see if 'val' was being assigned)
Losing sleep from trying to apply after() function
Code (I tried to strip down to essentials best I could, my problem is near the bottom):
'''
import tkinter as tk
import tkinter.messagebox
kk = 1
class App(tk.Tk):
WIDTH = 1000
HEIGHT = 520
def __init__(self):
super().__init__()
self.geometry(f"{App.WIDTH}x{App.HEIGHT}")
self.protocol("WM_DELETE_WINDOW", self.on_closing) # call .on_closing() when app gets closed
self.fr0 = tk.Frame(master=self, background = 'grey')
self.fr0.pack(fill = 'both', expand = True, padx = 20, pady = 20)
# configure grid layout (2x1)
self.fr0.columnconfigure(0, weight = 1)
self.fr0.columnconfigure(1, weight = 1)
self.fr0.rowconfigure((1,2,3), weight = 1)
# Title
self.lab_bcwt = tk.Label(self.fr0, text = 'Title', font=("Roboto Medium", 40), justify = 'center')
self.lab_bcwt.grid(row = 0,rowspan = 2, columnspan = 2)
# ===============================
self.fr1 = tk.Frame(self.fr0)#, fg_color=("black","grey"))
self.fr1.grid(row=2, rowspan = 2, columnspan = 2, sticky = 'nsew', padx = 10, pady = 10)
self.fr1.columnconfigure(0, weight = 1)
self.fr1.columnconfigure(1, weight = 1)
self.fr1.rowconfigure((0,1,2,3,4,5), weight = 1)
# ===============================
self.fr2 = tk.Frame(self.fr1)
self.fr2.grid(row=0, columnspan = 2, sticky = 'new', padx = 10, pady = 10)
self.fr2.grid_rowconfigure(0, weight = 1)
self.fr2.grid_columnconfigure(0, weight = 1)
# ===============================
self.lab1 = tk.Label(self.fr2, text = 'This text appears first\n (click to continue)', font=("Ariel", -22), justify = 'center')
self.lab1.grid( row = 0, columnspan = 2, padx = 10, pady = 5)
self.bind("<Button-1>",self.click)
def on_closing(self, event=0):
self.destroy()
def exmp_gps(self):
self.lab1.destroy()
self.lab2 = tk.Label(self.fr2, text = 'Then this text appears second,\n telling you to input an integer', font=('Ariel', -22))
self.lab2.grid(row = 0, column = 0, sticky = 'new', padx = 10, pady = 10)
self.lab3 = tk.Label(self.fr1, text = 'Any Integer', borderwidth = 2, font = ('Ariel', 12))
self.lab3.grid(row = 1, column = 0, sticky = 'ne', padx = 10)
self.entry1 = tk.Entry(self.fr1, text = 'any integer', justify = 'center')
self.entry1.grid(row = 1, column = 1, sticky = 'nw',padx = 10)
self.entry1.configure(font = ('Arial Rounded MT Bold', 13))
def key_pressed(event):
global val
val = int(self.entry1.get())
# print(val)
self.entry1.bind("<KeyRelease>", key_pressed)
# Ideally
self.entry1.bind("<Return>", print(['Function using', val+1]))
def click(self,event):
global kk
if kk == 1:
self.exmp_gps()
if kk > 1:
print(['Function using', val+1])
if __name__ == "__main__":
app = App()
app.mainloop()
'''
There is few problems in code.
bind needs function's name without () but you use print() so it first runs print() (which returns None) and later it binds None to <Return>. You could bind lambda event:print(...) to run print() when you press Enter.
Code could be more readable if you would use normal self.val instead of global val and if normal function in class def key_pressed(self, event): instead of nested function.
Everytime when you click button then it runs clik() and it runs self.exmp_gps() and it creates new Entry. You should increase kk in click() to run self.exmp_gps() only once. And to make it more readable you could use ie. self.visible = False and later set self.visible = True
You think it can be simple to activate function 2000ms after last keypress - but it is not. It would have to use after() and remeber its ID and time when it was created (to delete it if next key will be pressed before 2000ms, and use new after()).
Using Enter is much, much simpler.
Full code with changes.
I added after() but I didn't test it - maybe in some situations it may run function many times.
import tkinter as tk
import tkinter.messagebox
class App(tk.Tk):
WIDTH = 1000
HEIGHT = 520
def __init__(self):
super().__init__()
self.geometry(f"{App.WIDTH}x{App.HEIGHT}")
self.protocol("WM_DELETE_WINDOW", self.on_closing) # call .on_closing() when app gets closed
self.fr0 = tk.Frame(master=self, background='grey')
self.fr0.pack(fill='both', expand=True, padx=20, pady=20)
# configure grid layout (2x1)
self.fr0.columnconfigure(0, weight=1)
self.fr0.columnconfigure(1, weight=1)
self.fr0.rowconfigure((1, 2, 3), weight=1)
# Title
self.lab_bcwt = tk.Label(self.fr0, text='Title', font=("Roboto Medium", 40), justify='center')
self.lab_bcwt.grid(row=0, rowspan=2, columnspan=2)
# ===============================
self.fr1 = tk.Frame(self.fr0)#, fg_color=("black","grey"))
self.fr1.grid(row=2, rowspan=2, columnspan=2, sticky='nsew', padx=10, pady=10)
self.fr1.columnconfigure(0, weight=1)
self.fr1.columnconfigure(1, weight=1)
self.fr1.rowconfigure((0, 1, 2, 3, 4, 5), weight=1)
# ===============================
self.fr2 = tk.Frame(self.fr1)
self.fr2.grid(row=0, columnspan=2, sticky='new', padx=10, pady=10)
self.fr2.grid_rowconfigure(0, weight=1)
self.fr2.grid_columnconfigure(0, weight=1)
# ===============================
self.lab1 = tk.Label(self.fr2, text='This text appears first\n (click to continue)', font=("Ariel", -22), justify='center')
self.lab1.grid(row=0, columnspan=2, padx=10, pady=5)
self.bind("<Button-1>", self.click)
self.val = 0
self.visible = False
self.after_id = None
def on_closing(self, event=0):
self.destroy()
def key_pressed(self, event):
self.val = int(self.entry1.get())
print('[key_pressed]', self.val)
if self.after_id:
print('[key_pressed] cancel after:', self.after_id)
self.after_cancel(self.after_id)
self.after_id = None
self.after_id = self.after(2000, self.process_data)
print('[key_pressed] create after:', self.after_id)
def process_data(self):
print('[process_data]')
def exmp_gps(self):
self.lab1.destroy()
self.lab2 = tk.Label(self.fr2, text='Then this text appears second,\n telling you to input an integer', font=('Ariel', -22))
self.lab2.grid(row=0, column=0, sticky='new', padx=10, pady=10)
self.lab3 = tk.Label(self.fr1, text='Any Integer', borderwidth=2, font=('Ariel', 12))
self.lab3.grid(row=1, column=0, sticky='ne', padx=10)
self.entry1 = tk.Entry(self.fr1, text='any integer', justify='center')
self.entry1.grid(row=1, column=1, sticky='nw', padx=10)
self.entry1.configure(font=('Arial Rounded MT Bold', 13))
self.entry1.bind("<KeyRelease>", self.key_pressed)
self.entry1.bind("<Return>", lambda event:print('[Return] Function using', self.val))
def click(self, event):
if not self.visible:
self.visible = True
self.exmp_gps()
else:
print('[click] Function using', self.val)
if __name__ == "__main__":
app = App()
app.mainloop()

Returning a selected value from a dynamically populated combobox as a global variable?

I'm trying to automate some work to process data that is brought in from SQL. Towards the start of my full code I found and altered the below class from elsewhere on the site to act as a smooth interface so others can use the code too.
The aim of this is to retrieve the desired 'MPAN' and a year from the options. The combo-boxes are populated exactly as I wished, however the problem comes when trying to retrieve the selected values as global variables, and close the GUI when clicking 'Submit', as it stands nothing happens and the values are not obtained, but there is no error produced.
My assumption would be I've made a mistake with my 'getMPAN' function, though I am not very experienced with this level of tkinter so would greatly apprciate a hand. For simplicity sake I have added the category dictionary to act as mock data.
b2=[[2018],[2019],[2020],[2021],[2022],[2023],[2024],[2025]]
category = {'home': ['utilities','rent','cable'],
'car': ['gas','oil','repairs'],
'rv':['parks','maintenance','payment']}
params=''
mpan=''
year=''
class Application(Frame):
def __init__(self, master=None, Frame=None):
Frame.__init__(self, master)
super(Application,self).__init__()
self.grid(column = 5,row = 20,padx = 50,pady = 50)
self.createWidgets()
def getUpdateData(self, event):
self.AccountCombo['values'] = category[self.CategoryCombo.get()]
self.AccountCombo.current(0)
def createWidgets(self):
tk.Label(text = 'Area Code:').grid(row = 2,column = 1,padx = 10)
tk.Label(text = 'MPAN:').grid(row = 4,column = 1,padx = 10)
tk.Label(text = 'Year:').grid(row = 6, column = 1, padx = 10)
self.AccountCombo = ttk.Combobox( width = 15)
self.AccountCombo.grid(row = 5,column = 1,pady = 25,padx = 10)
self.CategoryCombo = ttk.Combobox(width = 15, values = list(category.keys()))
self.CategoryCombo.bind('<<ComboboxSelected>>', self.getUpdateData)
self.CategoryCombo.grid(row = 3,column = 1,padx = 10,pady = 25)
self.YearCombo = ttk.Combobox(width = 15, values = b2)
self.YearCombo.grid(row = 7, column = 1, padx = 10, pady = 25)
self.YearCombo.current(0)
def getMPAN(self):
mpan=self.AccountCombo.get()
year=self.YearCombo.get()
self.destroy()
global params
params=[mpan,year]
w=tk.Button(Application(), text='Submit', command=Application().getMPAN)
w.grid(row=8, column=1)
app = Application()
app.master.title('MPAN Selector')
app.mainloop()
This is my first time posting on the site so I apologise if I'm missing any details. I've seen similar questions but none with solutions for this situation.
Figured out where I was going wrong.
Needed to bring the button inside the createWidgets function in order to correctly get the selected values from the ComboBox.
As to closing the widgets with the buttons command i simply needed to add the following line to the init:
self.master=master
Then in the getMPAN function changing the destroy to:
self.master.destroy()
I'm sure this is relatively sloppy fix but in total this was my code:
b2=[[2018],[2019],[2020],[2021],[2022],[2023],[2024],[2025]]
category = {'home': ['utilities','rent','cable'],
'car': ['gas','oil','repairs'],
'rv':['parks','maintenance','payment']}
params=''
mpan=''
year=''
class Application(tk.Frame):
def __init__(self, master=None, Frame=None):
Frame.__init__(self, master)
self.master=master
super(Application,self).__init__()
self.grid(column = 5,row = 20,padx = 50,pady = 50)
self.createWidgets()
def getUpdateData(self, event):
self.AccountCombo['values'] = category[self.CategoryCombo.get()]
self.AccountCombo.current(0)
def createWidgets(self):
tk.Label(text = 'Area Code:').grid(row = 2,column = 1,padx = 10)
tk.Label(text = 'MPAN:').grid(row = 4,column = 1,padx = 10)
tk.Label(text = 'Year:').grid(row = 6, column = 1, padx = 10)
self.AccountCombo = ttk.Combobox( width = 15)
self.AccountCombo.grid(row = 5,column = 1,pady = 25,padx = 10)
self.CategoryCombo = ttk.Combobox(width = 15, values = list(category.keys()))
self.CategoryCombo.bind('<<ComboboxSelected>>', self.getUpdateData)
self.CategoryCombo.grid(row = 3,column = 1,padx = 10,pady = 25)
self.YearCombo = ttk.Combobox(width = 15, values = b2)
self.YearCombo.grid(row = 7, column = 1, padx = 10, pady = 25)
self.YearCombo.current(0)
button=ttk.Button(self, text='Submit', command=self.getMPAN)
button.grid(row=9, column=1)
def getMPAN(self):
mpan=self.AccountCombo.get()
year=self.YearCombo.get()
self.master.destroy()
global params
params=[mpan,year]
w=tk.Button(Application(), text='Submit', command=Application().getMPAN)
w.grid(row=8, column=1)
app = Application()
app.master.title('MPAN Selector')
app.mainloop()

Getting and calculating stuff through tkinter widets

I was wondering how to calculate stuff using tkinter buttons. I'm making a simple program to calculate seconds to hours:minutes:seconds. The user inputs an integer using the entry widget on the seconds box and when they press calculate, they get the result via the converted time line. I'm confused on how to start calculating it. I know you get the integer via .get, but I'm stuck on how to do that and calculate it in a h:m:s format. This is my code so far.
import tkinter
from tkinter import *
class TimeConverterUI():
def __init__(self):
self.root_window = Tk()
self.root_window.geometry('400x150')
self.root_window.title('Seconds Converter')
self.text()
self.calculate_button()
self.quit_button()
self.root_window.wait_window()
def text(self):
row_label = tkinter.Label(
master = self.root_window, text = 'Seconds: ')
row_label.grid( row = 0, column = 0, columnspan=2, padx=10, pady=10,
sticky = tkinter.W)
secondsEntry = Entry(master = self.root_window)
secondsEntry.grid(row = 0, column = 1)
row_label = tkinter.Label(
master = self.root_window, text = 'Converted Time(H:M:S): ').grid(row=1)
def calculate_button(self):
quit = Button(self.root_window, text = "Calculate", command = self.calculate)
quit.grid(row = 3, column = 0, columnspan = 3, pady=20,
sticky = tkinter.W)
def calculate(self):
pass
def quit_button(self):
quit = Button(self.root_window, text = "Quit", command = self.quit)
quit.grid(row = 3, column = 3, columnspan = 3, pady=20,
sticky = tkinter.E)
def quit(self) -> bool:
self.root_window.destroy()
return True
if __name__ == '__main__':
convert=TimeConverterUI()
First break this code below into 2 lines if you ever want to use row_label later because this will return NoneType. You should define it first then use .grid on it (just like your button).
row_label = tkinter.Label(
master = self.root_window, text = 'Converted Time(H:M:S): ').grid(row=1)
Now you can create another label to show the result. Remember to put self. before its name so you can use it in the calculate function. Also change secondsEntry to self.secondsEntry for the same reason.Now you just use int(self.secondsEntry.get()) in that function and do the required calculations. Then set the result to that result label with .configure(text=str(result))

How to display output of print() in GUI python

I am new in creating GUI. I am doing it in Python with Tkinter. In my program I calculate following characteristics
def my_myfunction():
my code ...
print("Centroid:", centroid_x, centroid_y)
print("Area:", area)
print("Angle:", angle)
I would like to ask for any help/tips how to display those values in GUI window or how to save them in .txt file so that I can call them in my GUI
Thanks in advance
Tkinter is easy and an easy way to do a GUI, but sometimes it can be frustrating. But you should have read the docs before.
However, you can do in this way.
from tkinter import *
yourData = "My text here"
root = Tk()
frame = Frame(root, width=100, height=100)
frame.pack()
lab = Label(frame,text=yourData)
lab.pack()
root.mainloop()
There are several ways to display the results of any operation in tkiner.
You can use Label, Entry, Text, or even pop up messages boxes. There are some other options but these will probably be what you are looking for.
Take a look at the below example.
I have a simple adding program that will take 2 numbers and add them together. It will display the results in each kind of field you can use as an output in tkinter.
import tkinter as tk
from tkinter import messagebox
class App(tk.Frame):
def __init__(self, master):
self.master = master
lbl1 = tk.Label(self.master, text = "Enter 2 numbers to be added \ntogether and click submit")
lbl1.grid(row = 0, column = 0, columnspan = 3)
self.entry1 = tk.Entry(self.master, width = 5)
self.entry1.grid(row = 1, column = 0)
self.lbl2 = tk.Label(self.master, text = "+")
self.lbl2.grid(row = 1, column = 1)
self.entry2 = tk.Entry(self.master, width = 5)
self.entry2.grid(row = 1, column = 2)
btn1 = tk.Button(self.master, text = "Submit", command = self.add_numbers)
btn1.grid(row = 2, column = 1)
self.lbl3 = tk.Label(self.master, text = "Sum = ")
self.lbl3.grid(row = 3, column = 1)
self.entry3 = tk.Entry(self.master, width = 10)
self.entry3.grid(row = 4, column = 1)
self.text1 = tk.Text(self.master, height = 1, width = 10)
self.text1.grid(row = 5, column = 1)
def add_numbers(self):
x = self.entry1.get()
y = self.entry2.get()
if x != "" and y != "":
sumxy = int(x) + int(y)
self.lbl3.config(text = "Sum = {}".format(sumxy))
self.entry3.delete(0, "end")
self.entry3.insert(0, sumxy)
self.text1.delete(1.0, "end")
self.text1.insert(1.0, sumxy)
messagebox.showinfo("Sum of {} and {}".format(x,y),
"Sum of {} and {} = {}".format(x, y, sumxy))
if __name__ == "__main__":
root = tk.Tk()
myapp = App(root)
root.mainloop()

Issue with crash in TKinter Application

I have a program running that is having issues when the timer runs. Every time "start" is hit, the application crashes. Any thoughts?
##-- Imports --##
import time
import openpyxl as xl
from Tkinter import *
##-- Classes --##
class App(Frame):
def startTimer(self):
self.check = True
self.now = time.strftime("%H:%M:%S")
while self.check == True:
self.timer.configure(text = self.now)
time.sleep(1)
def initUI(self):
self.parent.title("Emma's Time Manager")
self.pack(fill = BOTH, expand = 1)
def initWidget(self):
##Create button definitions##
self.buttonwidth = 12
self.quit = Button(self, text = "Quit", comman = self.quit, width = self.buttonwidth)
self.newClient = Button(self, text = "Add Client", command = lambda:self.newClientFunc(), width = self.buttonwidth)
self.timeStart = Button(self, text = "Start", command = lambda:self.startTimer(), width = self.buttonwidth)
self.timeEnd = Button(self, text = "End", command = lambda:self.endTimer(), width = self.buttonwidth)
self.saveBut = Button(self, text = "Save", command = lambda:self.saveFunc(), width = self.buttonwidth)
self.viewClient = Button(self, text = "View Client", command = lambda:self.viewCliFunc(), width = self.buttonwidth)
##Create lable definitions##
self.timer = Label(self, text = "00:00:00") ##self.timer used as display for timer##
##Create the listbox for Client Selection##
self.wb = xl.load_workbook("clients.xlsx")
self.clientNames = self.wb.get_sheet_names()
self.clivar = StringVar(self)
self.clivar.set(self.clientNames[0])
self.clilist = apply(OptionMenu, (self, self.clivar) + tuple(self.clientNames))
##Create Entry Box to describe work information##
self.info = Entry(self, width = 50)
##Create GUI for widgets##
self.clilist.grid(row = 0, column = 0)
self.timer.grid(row = 0, column = 1)
self.timeStart.grid(row = 0, column = 2)
self.timeEnd.grid(row = 0, column = 3)
self.info.grid(row = 1, column = 0, columnspan = 4)
self.newClient.grid(row = 2, column = 0)
self.viewClient.grid(row = 2, column = 1)
self.saveBut.grid(row = 2, column = 2)
self.quit.grid(row = 2, column = 3)
def __init__(self, parent):
Frame.__init__(self, parent, background = "light blue")
self.parent = parent
self.initUI()
self.initWidget()
def main():
try:
xl.load_workbook("clients.xlsx")
except:
temp = xl.Workbook()
temp.save("clients.xlsx")
temp.remove_sheet(temp.get_sheet_by_name("Sheet"))
root = Tk()
bob = App(root)
root.mainloop()
main()
Please note that most of the program is not yet finished. I just cannot seem to get this timer to run properly.
Looks like you have no way out of your while loop. You'll either need to set self.check to False, or break out of the loop.
while self.check == True:
self.timer.configure(text = self.now)
time.sleep(1)

Categories