python tkinter - over writing label on button press - python

def button_pressed(item_name, item_price):
global lbl
for v1, v2 in zip(item_name, item_price):
item_values = '{} {}'.format(v1, v2)
sv = StringVar()
lbl = Label(shop_window, height="2", textvariable=sv, anchor = NW).grid(columnspan = 4)
sv.set(item_values)
# Create initial shopping cart window
shop_window = Tk()
shop_window.title('Welcome to the Outlet')
shop_window.geometry("1200x900")
shop_window.resizable(0, 0)
introduction_text = Label(shop_window, text = 'Welcome to the Shopping Outlet', font = ('Arial', 30))
electronics_button = Button(shop_window, text = 'Buy Electronics', font = ('Arial', 18), command = lambda:button_pressed(electronics_name, electronics_price))
books_button = Button(shop_window, text = 'Buy Books', font = ('Arial', 18), command = lambda:button_pressed(books_name, books_price))
kitchen_button = Button(shop_window, text = 'Buy Kitchen', font = ('Arial', 18), command = lambda:button_pressed(kitchen_name, kitchen_price))
monitors_button = Button(shop_window, text = 'Buy Kitchen', font = ('Arial', 18), command = lambda:button_pressed(monitors_name, monitors_price))
introduction_text.grid(row = 0, column = 0, columnspan = 4, sticky = N )
electronics_button.grid(row = 2, column = 0)
books_button.grid(row = 2, column = 1)
kitchen_button.grid(row = 2, column =2)
monitors_button.grid(row = 2, column = 3)
I've created this tk window to display a shopping list of 10 items per category. Each category has two list, item_name/item_price (they have been scraped off amazon.)
When I run the program I can press the button and the list will display properly but if I press it again it adds new labels to the end of the previously made labels. My questions would be how do I make the program overwrite previous labels for example. Press "Buy Electronics" creates my labels as required, but pressing "Buy Books" after adds more labels. I want to over write the "Buy Electronics" labels. I figured it would be some kind of global lbl but unsure.

You could create a frame for the labels
f = Frame(shop_window)
f.grid(row=3, column=0, columnspan=4)
Then in the callback function destroy all children of the frame and create new ones
def button_pressed(item_name, item_price):
for widget in f.winfo_children():
widget.destroy()
for v1, v2 in zip(item_name, item_price):
item_values = '{} {}'.format(v1, v2)
Label(f, height="2", text=item_values).pack()

see the on the example with function have created, to do that you need to overwrite before positioning the current one there by using lbl["text"] = sv
def button_pressed(item_name, item_price):
global lbl
for v1, v2 in zip(item_name, item_price):
item_values = '{} {}'.format(v1, v2)
# sv = StringVar()
lbl["text"] = sv
sv.set(item_values)
Then create you Label inside root and mainloop
shop_window = Tk()
sv = StringVar()
lbl = Label(shop_window, height="2", textvariable=sv, anchor = NW)
lbl.grid(columnspan = 4)
shop_window = Tk()

Related

Why does the entry widget not work in this case i put it in a frame, tkinter-python

So this is a basic clock and alarm that i am creating, and in the process i want the user to type in what hour and minute they want to set for the alarm. But the entry widget here is not responding.
import time
import tkinter as tk
current_date, current_time = 0, 0
def current_info(timeinfo): #function to get the current time and date
global current_date, current_time
# current time
current_time = time.strftime('%H:%M:%S')
current_date = time.strftime(r'%m/%d/%Y')
clock.after(200, timeinfo)
#Initialise the window
clock = tk.Tk()
clock.title('Easy CLock')
clock.configure(bg='#121212')
clock.columnconfigure(0, weight = 1)
clock.columnconfigure(1, weight = 1)
clock.columnconfigure(2, weight = 1)
clock.columnconfigure(3, weight = 1)
border_effects = {
"flat": tk.FLAT,
"sunken": tk.SUNKEN,
"raised": tk.RAISED,
"groove": tk.GROOVE,
"ridge": tk.RIDGE,
}
#Logo will be under the main parent
logo = tk.PhotoImage(file = r'C:\Users\User\VSC\Alarm\Logo1.png')
logo_size = logo.subsample(5)
#Time and Date function
def time_date():
current_info(time_date)
#Displays the time
c_time = tk.Label(f_time, text = current_time, fg='white', bg='#121212', font=('Verdana', 30))
c_date = tk.Label(f_time, text = current_date, font=('Verdana', 10), fg='white', bg='#121212')
c_time.grid(column=0, row=0)
c_date.grid(column=0, row=1)
#alarm button command
def alarm_func():
current_info(alarm_func)
c_time = tk.Label(f_alarm, text = current_time, fg='white', bg='#121212', font=('Verdana', 10))
c_date = tk.Label(f_alarm, text = current_date, font=('Verdana', 10), fg='white', bg='#121212')
def pressed_enter(): #Command for the enter button
set_label = tk.Label(f_alarm, text = f'Alarm has been set for {time_set}', fg ='white', bg = '#121212', borderwidth = 1, relief = border_effects['sunken'])
set_label.grid(column = 4, row = 0, sticky = 'W')
# Set the time and date for the alarm
set_time = tk.StringVar()
alarm_entry = tk.Entry(clock, textvariable = set_time)
set_time.set('H : M')
time_set = alarm_entry.get()
#label and entry to set alarm / Enter Button
c_label = tk.Label(f_alarm, text = 'Set Alarm: ', font = ('Verdana', 10), fg= 'white', bg ='#121212' )
alarm_enter = tk.Button(f_alarm, text = 'Enter', font = ('Verdana', 7), width = 5, command = pressed_enter)
#Pack the widgets
c_time.grid(row = 0, column = 0)
c_date.grid(column = 1 , row = 0)
alarm_enter.grid(row = 2, column = 3)
c_label.grid(row = 2, sticky = 'W')
alarm_entry.grid(row = 2, column = 1)
#configure the empty columns
f_alarm.columnconfigure(2, minsize = 10)
def recall_frame(event):
if event == f_alarm:
event.grid_forget()
f_time.grid(column=0, row =1, columnspan = 4, sticky = 'N')
elif event == f_time:
event.grid_forget()
f_alarm.grid(column=0, row=1, columnspan = 4, sticky = 'W')
def back_func():
pass
#Creating Frames
f_time = tk.Frame(clock) #Clock Button
f_alarm = tk.Frame(clock) #Alarm Buttton
#configure the frames
f_time.configure(bg = '#121212')
f_alarm.configure(bg = '#121212')
#Setting label in the frame
f_lbl = tk.Label(clock, text= ' Simplistic Clock', image = logo_size, font=('Verdana', 30), fg='white', bg='#121212', compound = tk.LEFT, padx = 35)
time_but = tk.Button(clock, text='Clock', command= lambda :[time_date(), recall_frame(f_alarm)], bg='#f39c12', relief = border_effects['ridge'], pady = 7)
alarm_but = tk.Button(clock, text = 'Alarm', command = lambda :[alarm_func(), recall_frame(f_time)], bg='#f39c12', relief = border_effects['ridge'], pady = 7)
quit_but = tk.Button(clock, text='Exit', command = clock.quit, bg='#f39c12', relief = border_effects['ridge'], pady = 7)
back_but = tk.Button(clock, text = 'Back ', command = back_func, bg='#f39c12', relief = border_effects['ridge'], pady = 7)
f_lbl.config(borderwidth = 4, relief = border_effects['sunken'])
#Putting it on the frames
f_lbl.grid(column = 0, row = 0, columnspan = 5, sticky = 'EW')
time_but.grid(column = 0, row = 3, sticky = 'EW')
alarm_but.grid(column = 1, row = 3, sticky = 'EW')
quit_but.grid(column = 3, row = 3, sticky = 'EW')
back_but.grid(column = 2, row = 3, sticky = 'EW')
clock.mainloop()
i tried testing an entry widget outside the frame and the entry widget was able to work, is it because the frame f_alarm is not looping constantly in the background?
When someone clicks on your button which activates the pressed_enter() function, it will call that function again every time which will set the time to H:M and it will get that value as the set_time.get() is called immediately after.
You're also creating a new Entry every time the button is being clicked because you put alarm_entry = tk.Entry(clock, textvariable=set_time)
in there as well. You should only put the set_time.get inside of that button so that it gets the value that is currently filled in into the Entry. The other things like
set_time = tk.StringVar()
alarm_entry = tk.Entry(clock, textvariable=set_time)
set_time.set('H : M')
Should be put outside of that function so they don't get called every time someone clicks on the button.

How do I format my GUI using tkinter by using .grid?

I am trying to use .grid to format my GUI, but it is not doing anything. Here below is my code and my desired layout!
Here is the code I am using. I am quite new to Python...
I am not sure of other methods of formatting except for .grid so any other options would be great too!
from tkinter import *
class PayrollSummary:
def __init__(pay):
window = Tk()
window.title("Employee Payroll")
#Add Frame 1
frame1 = Frame(window)
frame1.pack()
#Add ReadFile Button
btReadFile = Button(frame1, text = "Read File")
btReadFile.pack()
#Add ShowPayroll Button
btShowPayroll = Button(frame1, text = "Show Payroll")
btShowPayroll.pack()
#Add FindEmployee by Name Button
btFindEmployee = Button(frame1, text = "Find Employee by Name")
btFindEmployee.pack()
#Add Highest Radio Button
rbHigh = Radiobutton(frame1, text = "Highest")
rbHigh.pack()
#Add Lowest Radio Button
rbLow = Radiobutton(frame1, text ="Lowest")
rbLow.pack()
#Add FindEmployee by Amount Button
btFindEmployee_A = Button(frame1, text = "Find Employee by Amount")
btFindEmployee_A.pack()
#Add WriteOutput Button
btOutput = Button(frame1, text = "Write Output to File")
btOutput.pack()
#Add Cancel Button
btCancel = Button(frame1, text = "Cancel")
btCancel.pack()
btReadFile.grid(row = 1, column = 2)
btShowPayroll.grid(row = 2, column = 2)
btFindEmployee.grid(row = 2, column = 4)
rbHigh.grid(row = 3, column = 2)
rbLow.grid(row = 3, column = 4)
btFindEmployee_A.grid(row = 3, column = 6)
btOutput.grid(row = 4, column = 2)
btCancel.grid(row = 4, column = 4)
window.mainloop()
PayrollSummary()
pack(), grid() and place() are three methods to put widgets in window (or in other widget).
If you use grid() with some widget then don't use pack() or place().
Doc on effbot.org: grid, pack, place
I removed all .pack() except frame.pack() and get almost what you expected.
Now widgets need to be aligned to left ('west') with sticky='w'
And after adding second Frame I got
Code:
from tkinter import *
class PayrollSummary:
def __init__(pay):
window = Tk()
window.title("Employee Payroll")
#Add Frame 1
frame1 = Frame(window)
frame1.pack()
#Add ReadFile Button
btReadFile = Button(frame1, text = "Read File")
#Add ShowPayroll Button
btShowPayroll = Button(frame1, text = "Show Payroll")
#Add FindEmployee by Name Button
btFindEmployee = Button(frame1, text = "Find Employee by Name")
#Add Highest Radio Button
rbHigh = Radiobutton(frame1, text = "Highest")
#Add Lowest Radio Button
rbLow = Radiobutton(frame1, text ="Lowest")
#Add FindEmployee by Amount Button
btFindEmployee_A = Button(frame1, text = "Find Employee by Amount")
#Add WriteOutput Button
btOutput = Button(frame1, text = "Write Output to File")
#Add Cancel Button
btCancel = Button(frame1, text = "Cancel")
btReadFile.grid(row = 1, column = 2, sticky='w')
btShowPayroll.grid(row = 2, column = 2, sticky='w')
btFindEmployee.grid(row = 2, column = 4, sticky='w')
rbHigh.grid(row = 3, column = 2, sticky='w')
rbLow.grid(row = 3, column = 4, sticky='w')
btFindEmployee_A.grid(row = 3, column = 6, sticky='w')
btOutput.grid(row = 4, column = 2, sticky='w')
btCancel.grid(row = 4, column = 4, sticky='w')
#Add Frame 2
frame2 = Frame(window, bg='red')
frame2.pack(fill='both') # try without `fill`
label2 = Label(frame2, text='Label in bottom Frame', bg='green')
label2.pack()
window.mainloop()
PayrollSummary()

Tkinter buttons not performing command [duplicate]

This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 4 years ago.
I am trying to create a counter for Jeopardy so that my Mom and I can keep score. Currently the program that I am creating is assigning the values to variables and then not performing the command when I press the button in the window. I am running Python 2.7.13.`
import Tkinter as tk
root = tk.Tk()
root.title("Jeopardy Scores")
def ChangeScore(User,Value):
if User == 1:
Score = int(JScore.get())
JScore.set(Score + Value)
#J = JScore.get()
#print J
#SayHi()
else:
Score = int(MScore.get())
MScore.set(Score + Value)
#M = MScore.get()
#print M
#SayHi()
#def SayHi(*args):
#print 'hi'
MainFrame = tk.Frame(root)
MainFrame.grid(column=0, row=0)
MainFrame.columnconfigure(0, weight=1)
MainFrame.rowconfigure(0, weight=1)
JScore = tk.StringVar()
MScore = tk.StringVar()
JScore.set(0)
MScore.set(0)
JL = tk.Label(MainFrame, text = "Joey's Score", padx = 10, pady = 2)
JL.config(bg = 'blue', fg = 'yellow', font = ('Arial',30, 'bold'))
JL.grid(column = 0, row = 0)
ML = tk.Label(MainFrame, text = "Mom's Score", padx = 10, pady = 2)
ML.config(bg = 'blue', fg = 'yellow', font = ('Arial',30, 'bold'))
ML.grid(column = 1, row = 0)
JSS = tk.Label(MainFrame, textvariable=JScore ,padx = 122)
JSS.config(bg = 'blue', fg = 'yellow', font = ('Arial',30, 'bold'))
JSS.grid(column = 0, row = 1)
MSS = tk.Label(MainFrame, textvariable = MScore,padx = 122)
MSS.config(bg = 'blue', fg = 'yellow', font = ('Arial',30, 'bold'))
MSS.grid(column = 1, row = 1)
for i in range(1,6):
Score = tk.IntVar()
Score.set(i*200)
Score1 = 200*i
JButton = tk.Button(MainFrame, textvariable = Score, command =
ChangeScore(1,Score1))
JButton.grid(column = 0, row = 1+i)
MButton = tk.Button(MainFrame, textvariable = Score, command =
ChangeScore(2,Score1))
MButton.grid(column = 1, row = 1+i)
JButton = tk.Button(MainFrame, text = '400', command = ChangeScore(1,400))
JButton.grid(column = 0, row = 7)
root.mainloop()
The code runs and produces this Window
Note that no buttons have been pressed when the picture was taken. It appears that all the buttons are 'being pressed' when the code runs and then nothing happens when i press the buttons afterwards.
I have no experience with Tkinter beyond the small information that has allowed me to do this and I have a bit more experience with Python. I am mainly doing this as an excerise for myself to improve my coding and to acutally use for Jeopardy!. Any help would be appreciate
Here the command parameter for Button should be a callable. You should not call the function yourself and pass the return value to it. Instead, you provide a function that is to be called later.
So change you code to things like
command=lambda: ChangeScore(1, 400)
to create a lambda to be called later will solve the problem.

OptionMenu in tkinter keeps crashing when placed in a frame

I am trying to place an OptionMenu widget inside of a frame, which itself is inside of a notebook. From what I've found online, the code for doing this is roughly:
# add a drop down menu
hops = range(0,6)
self.selectedHop = StringVar(frame2)
self.selectedHop.set(hops[0])
self.hopOptions = OptionMenu(frame2, self.selectedHop, *hops)
self.hopOptions.grid(row=0, column=2, sticky=EW)
However, when I place this in my code in the code below (the chunk above is placed towards the bottom of it, and is labeled "PROBLEMATIC CODE..."), my app just freezes and I have to force quit it, and I have no error message to debug with. Any help would be appreciated.
#!/usr/bin/python3
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import subprocess
import sys
class ReportGUI:
def __init__(self, master):
self.master = master
master.title('Reporting')
master.resizable(True, True)
master.configure(background = '#b3e6cc')
master.minsize(width=800,height=700)
textcolor = "#003399"
self.style = ttk.Style()
self.style.configure('TFrame', background = '#e1d8b9')
self.style.configure('TButton', background = '#e1d8b9')
self.style.configure('TLabel', background = '#e1d8b9', font = ('Arial', 40))
self.style.configure('Header.TLabel', font = ('Arial', 30, 'bold'))
# step 1 - create notebook
self.notebook = ttk.Notebook(master)
self.notebook.pack()
# step 2 - create first frame to add to notebook
self.frame_logon = ttk.Frame(self.notebook)
# step 3 - add first frame to notebook and style it
self.notebook.add(self.frame_logon, text = 'Login')
self.frame_logon.config(padding = (20, 20, 20))
self.frame_logon.config(relief = RIDGE)
######### --- (1) LOGIN TAB ---- #########
label = ttk.Label(self.frame_logon, text = 'Administrative Reporting',
foreground=textcolor, style = 'Header.TLabel')
label.grid(row = 1, columnspan = 2)
# widget: username and password Label()
label2 = ttk.Label(self.frame_logon, text = 'Username:',
font = ('Arial', 17),foreground=textcolor)
label2.grid(row = 3, column = 0, padx = 5, sticky = 'sw')
label3 = ttk.Label(self.frame_logon, text = 'Password:',
font = ('Arial', 17),foreground=textcolor)
label3.grid(row = 3, column = 1, padx = 5, sticky = 'sw')
# widget: entry boxes Entry()
self.entry_name = ttk.Entry(self.frame_logon, width = 20, font = ('Arial', 15))
self.entry_pw = ttk.Entry(self.frame_logon, width = 20, font = ('Arial', 15))
# place the widgets
self.entry_name.grid(row = 4, column = 0, padx = 5)
self.entry_pw.grid(row = 4, column = 1, padx = 5)
self.entry_pw.config(show = '*') # make password not show
# widget: connect button Button()
self.loginButton = ttk.Button(self.frame_logon, text = 'Connect',
command = self.login)
self.loginButton.grid(row = 5, column = 1, columnspan = 2, padx = 1, pady = 1, sticky = 'e')
### COMMAND FUNCTIONS
def login(self):
# Make connections (TBA)
# 1) log into app
# 2) ssh into server port
# 3) connect to database
# if successful login and connection, launch reports tab
self.reportTab()
self.notebook.select(1) # switch tabs to reports tab
self.loginButton.state(['disabled']) # disable login button
# TAB 2: reporting tab
def reportTab(self):
# create report frame and add to notebook
self.frame_report = ttk.Frame(self.notebook)
self.notebook.add(self.frame_report, text = 'Report Options')
######### --- REPORT TAB ---- #########
#--------- FILTER 1: -----------
frame = ttk.Frame(self.frame_report)
frame.grid(row=1,column=0)
frame.config(height = 100, width = 200)
frame.config(relief = RIDGE)
ttk.LabelFrame(frame, height=100,width = 200,text = 'FILTER 1').pack()
#--------- FILTER 2: -----------
frame2 = ttk.Frame(self.frame_report)
frame2.grid(row=1,column=1)
frame2.config(height = 100, width = 200)
frame2.config(relief = RIDGE)
ttk.LabelFrame(frame2, height=100,width = 200,text = 'FILTER 2').pack()
#---------- PROBLEMATIC CODE: trying to add a drop down menu ----
hops = range(0,6)
self.selectedHop = StringVar(frame2)
self.selectedHop.set(hops[0])
self.hopOptions = OptionMenu(frame2, self.selectedHop, *hops)
self.hopOptions.grid(row=0, column=2, sticky=EW)
#----------------------------------------------------------------
#--------- FILTER 3: -----------
frame3 = ttk.Frame(self.frame_report)
frame3.grid(row=2,column=0)
frame3.config(height = 100, width = 200)
frame3.config(relief = RIDGE)
lbf3 = ttk.LabelFrame(frame3, height=100,width = 200,text = 'FILTER 3')
lbf3.pack()
#--------- FILTER 4: -----------
frame4 = ttk.Frame(self.frame_report)
frame4.grid(row=2,column=1)
frame4.config(height = 100, width = 200)
frame4.config(relief = RIDGE)
ttk.LabelFrame(frame4, height=100,width = 200,text = 'FILTER 4').pack()
# code for calling queries TBA
# launch results tab if queries successful
# self.resultsTab()
def func(self,value):
print(value)
# TAB 3: results tab
def resultsTab(self):
# create results frame and add to notebook
self.frame_results = ttk.Frame(self.notebook)
self.notebook.add(self.frame_results, text = 'Results')
def clear(self):
self.entry_name.delete(0, 'end')
self.entry_pw.delete(0, 'end')
self.text_comments.delete(1.0, 'end')
def main():
root = Tk()
hccwgui = ReportGUI(root)
root.mainloop()
if __name__ == "__main__": main()
Thanks in advance!
# ...
ttk.LabelFrame(frame2, height=100,width = 200,text = 'FILTER 2').pack()
# ...
self.hopOptions = OptionMenu(frame2, self.selectedHop, *hops)
self.hopOptions.grid(row=0, column=2, sticky=EW)
This is your problem. You're packing a LabelFrame in frame2, and then trying to grid something in frame2. A given container can only use one of grid() or pack()- using both won't cause an error, but the two managers will negotiate on how to place things for the rest of your lifetime.
The solution is to make sure that a given container's children are either packed or gridded, but never both in the same container (though you could have a structure parent->child->grandchild, where child is packed in parent and grandchild is gridded in child).

Radionbutton output reset and border that's not showing up

I am coding a python script that can display the buttons that I select to a label.
this program is containing 4 radiobutton and 1 label.
so far the problem of my program is that my program can not be repeated. Also I need to have a border surround the label.
I am using python 2.7 and I cannot post image because I don't have enough reputation
= Label(the_window, text = 'Null', fg = 'black',font = ('Times', 36), width = 8)
button.grid(row=2,column=1)
button.grid(row=3,column=1)
button.grid(row=2,column=2)
button.grid(row=3,column=2)
this is my setup
https://repl.it/BJcH
You can add a border to your label by specifying a relief:
direction_status = Label(the_window, text = 'Null', fg = 'black',
font = ('Times', 36), width = 8, relief=GROOVE)
Rather than using four BooleanVars as value attributes for your radio buttons, use a single IntVar. This will indicate to Tkinter that the radio buttons belong in the same group, and will ensure that only one can be selected at a time.
from Tkinter import *
# Create a window
the_window = Tk()
# Give the window a title
the_window.title('Compass')
##Label widget to display initial Compass's status
direction_status = Label(the_window, text = 'Null', fg = 'black',
font = ('Times', 36), width = 8)
## Function that define the label's text when radiobuttion is being selected
def update_the_window():
if v.get() == 1:
direction_status['text'] = 'NW'
if v.get() == 2:
direction_status['text'] = 'SW'
if v.get() == 3:
direction_status['text'] = 'NE'
if v.get() == 4:
direction_status['text'] = 'SE'
## Label Frame for direction_status
direction_status_frame = LabelFrame(the_window, relief = 'groove',
borderwidth = 2)
v = IntVar()
## 4 Buttons that change the status sorted by directions
NW_button = Radiobutton(text = 'North-West', variable = v,
value= 1, command=update_the_window, padx=20)
NW_button.pack(anchor=W)
SW_button = Radiobutton(text = 'South-West', variable = v,
value= 2, command = update_the_window, padx=20)
SW_button.pack(anchor=W)
NE_button = Radiobutton(text= 'North-East', variable = v,
value= 3, command=update_the_window, padx=20)
NE_button.pack(anchor=W)
SE_button = Radiobutton(text= 'South-East', variable = v,
value= 4, command=update_the_window, padx=20)
SE_button.pack(anchor=W)
## Grid geometry to put 4 radio buttons into the GUI
NW_button.grid(row=2,column=1)
SW_button.grid(row=3,column=1)
NE_button.grid(row=2,column=2)
SE_button.grid(row=3,column=2)
## Grid geometry manager to put the widget into the root window
margin = 5 ##pixels
direction_status.grid(padx=margin, pady=margin, row=1, column=1, columnspan=2)
#--------------------------------------------------------------------#
# Start the event loop to react to user inputs
the_window.mainloop()
You could also use a StringVar instead, which cuts down on the size of update_the_window somewhat.
from Tkinter import *
# Create a window
the_window = Tk()
# Give the window a title
the_window.title('Compass')
# PUT YOUR CODE HERE-------------------------------------------------#
##Label widget to display initial Compass's status
direction_status = Label(the_window, text = 'Null', fg = 'black',
font = ('Times', 36), width = 8)
## Function that define the label's text when radiobuttion is being selected
def update_the_window():
direction_status['text'] = direction.get()
direction = StringVar()
direction.set("NW")
update_the_window()
## Label Frame for direction_status
direction_status_frame = LabelFrame(the_window, relief = 'groove',
borderwidth = 2)
## 4 Buttons that change the status sorted by directions
NW_button = Radiobutton(text = 'North-West', variable = direction,
value= "NW", command=update_the_window, padx=20)
NW_button.pack(anchor=W)
SW_button = Radiobutton(text = 'South-West', variable = direction,
value= "SW", command = update_the_window, padx=20)
SW_button.pack(anchor=W)
NE_button = Radiobutton(text= 'North-East', variable = direction,
value= "NE", command=update_the_window, padx=20)
NE_button.pack(anchor=W)
SE_button = Radiobutton(text= 'South-East', variable = direction,
value= "SE", command=update_the_window, padx=20)
SE_button.pack(anchor=W)
## Grid geometry to put 4 radio buttons into the GUI
NW_button.grid(row=2,column=1)
SW_button.grid(row=3,column=1)
NE_button.grid(row=2,column=2)
SE_button.grid(row=3,column=2)
## Grid geometry manager to put the widget into the root window
margin = 5 ##pixels
direction_status.grid(padx=margin, pady=margin, row=1, column=1, columnspan=2)
#--------------------------------------------------------------------#
# Start the event loop to react to user inputs
the_window.mainloop()

Categories