Programming Exercise 3-1
Programming Exercise 13-7
import tkinter
import tkinter.messagebox
class LongDistanceGUI:
def __init__(self):
# Create the main window
self.main_window = tkinter.Tk()
# Create frames
self.top_frame = tkinter.Frame(self.main_window)
self.mid_frame = tkinter.Frame(self.main_window)
self.bottom_frame = tkinter.Frame(self.main_window)
# Create variable to use with the Radiobuttons
self.rb_var = tkinter.IntVar()
# Set the variable to 1
self.rb_var.set(1)
# Create the Radiobuttons in top_frame
self.rb1 = tkinter.Radiobutton \
(self.top_frame, \
text = ‘Daytime (6:00am – 5:59pm)’, \
variable = self.rb_var, value = 1)
self.rb2 = tkinter.Radiobutton \
(self.top_frame, \
text = ‘Evening (6:00pm – 11:59pm)’, \
variable = self.rb_var, value = 2)
self.rb3 = tkinter.Radiobutton \
(self.top_frame, \
text = ‘Off-Peak (12:00am – 5:59am)’, \
variable = self.rb_var, value = 3)
# Pack the Radiobuttons
self.rb1.pack()
self.rb2.pack()
self.rb3.pack()
# Create the widgets for mid_frame
self.minutes_label = tkinter.Label \
(self.mid_frame, \
text = ‘Enter the number of minutes:’)
self.minutes_entry = tkinter.Entry(self.mid_frame, width = 10)
# Pack the value frame widgets
self.minutes_label.pack(side = ‘left’)
self.minutes_entry.pack(side = ‘left’)
# Create the two buttons in the bottom frame
self.display_button = tkinter.Button \
(self.bottom_frame, \
text = ‘Display Charges’, \
command = self.calculate)
self.quit_button = tkinter.Button \
(self.bottom_frame, \
text = ‘Quit’, \
command = self.main_window.destroy)
# Pack the widgets in the bottom frame
self.display_button.pack(side=’left’)
self.quit_button.pack(side=’left’)
# Pack the frames
self.top_frame.pack()
self.mid_frame.pack()
self.bottom_frame.pack()
# Enter the tkinter main loop
tkinter.mainloop()
# Define the calculate function
def calculate(self):
# Get the value entered
self.minutes = float(self.minutes_entry.get())
# Determine rate based on Radiobutton selected
if self.rb_var.get() == 1:
self.rate = 0.07
if self.rb_var.get() == 2:
self.rate = 0.12
if self.rb_var.get() == 3:
self.rate = 0.05
# Calculate charges
self.charges = self.minutes * self.rate
# Display message box
tkinter.messagebox.showinfo(‘Total Charges’, \
‘Your total charges = $’ + \
format(self.charges,’,.2f’))
# Create an instance of LongDistanceGUI
long_dist = LongDistanceGUI()