I was wondering how I could change button behavior based on which item in the drop down menu I have selected in the "Check Maintenance" tab. For example, when I have oil selected, I want the button to perform the check_oil_change() function. When it has spark plugs selected, I want the button to perform a different function that will handle that specific maintenance.
(sorry I had to rewrite my question)
from tkinter import *
from tkinter import ttk
#initializing root window
root = Tk()
root.title("Car Maintenance App")
root.resizable(False, False)
tab_control = ttk.Notebook(root)
tab1 = ttk.Frame(tab_control)
tab2 = ttk.Frame(tab_control)
tab_control.add(tab1, text="History")
tab_control.add(tab2, text="Check maintenance")
tab_control.pack(expand=1, fill="both")
#functions
miles = IntVar()
last_miles = IntVar()
miles_between_changes = 3000
def check_oil_change():
miles = miles_entry.get()
miles = int(miles)
last_miles = last_miles_entry.get()
last_miles = int(last_miles)
miles_till_oilchange = miles_between_changes - (miles - last_miles)
if miles_till_oilchange == 0:
output_label.config(text="You are due for an oil change")
if miles_till_oilchange > 0:
output_label.config(text="You have {} miles until next oil change.".format(miles_till_oilchange))
if miles_till_oilchange < 0:
output_label.config(text="You are over due {} miles for an oil change.".format(abs(miles_till_oilchange)))
#tab1 widgets
last_miles_label = ttk.Label(tab1, text= "How many miles was your last oil change at?")
last_miles_entry = ttk.Entry(tab1, width=7)
#tab1 positioning
last_miles_label.grid(row=0, column=0)
last_miles_entry.grid(row=0, column=1)
#tab2 widgets
miles_label = ttk.Label(tab2, text= "Enter your cars current mileage:")
miles_entry = ttk.Entry(tab2, width=7)
miles_button = ttk.Button(tab2, text="Enter", command=check_oil_change)
output_label = ttk.Label(tab2, text="")
maintenance_choices = [ #drop down menu options
"Oil change",
"Tire Rotation",
"Spark Plugs",
]
clicked = StringVar()
clicked.set( "Oil" )
maintenance_choices_dropdown = OptionMenu(tab2, clicked, *maintenance_choices)
#tab2 positioning
maintenance_choices_dropdown.grid(row=0, column=0, sticky="W")
miles_label.grid(row=1, column=0)
miles_entry.grid(row=1, column=1)
miles_button.grid(row=1, column=2)
output_label.grid(row=2, column=1)
root.mainloop()
I added a command attribute to Options Menu. Now, whenever an option is selected from the menu, it triggers the OptionMenu_SelectionEvent function. Now, within this function, you can change the command of the button which it triggers to.
from tkinter import *
from tkinter import ttk
#initializing root window
root = Tk()
root.title("Car Maintenance App")
root.resizable(False, False)
tab_control = ttk.Notebook(root)
tab1 = ttk.Frame(tab_control)
tab2 = ttk.Frame(tab_control)
tab_control.add(tab1, text="History")
tab_control.add(tab2, text="Check maintenance")
tab_control.pack(expand=1, fill="both")
#functions
miles = IntVar()
last_miles = IntVar()
miles_between_changes = 3000
def check_oil_change():
miles = miles_entry.get()
miles = int(miles)
last_miles = last_miles_entry.get()
last_miles = int(last_miles)
miles_till_oilchange = miles_between_changes - (miles - last_miles)
if miles_till_oilchange == 0:
output_label.config(text="You are due for an oil change")
if miles_till_oilchange > 0:
output_label.config(text="You have {} miles until next oil change.".format(miles_till_oilchange))
if miles_till_oilchange < 0:
output_label.config(text="You are over due {} miles for an oil change.".format(abs(miles_till_oilchange)))
def test():
print("Here")
def OptionMenu_SelectionEvent(value):
if value == 'Oil change':
miles_button['command']=test
elif value == 'Tire Rotation':
pass
elif value == 'Spark Plugs':
pass
#tab1 widgets
last_miles_label = ttk.Label(tab1, text= "How many miles was your last oil change at?")
last_miles_entry = ttk.Entry(tab1, width=7)
#tab1 positioning
last_miles_label.grid(row=0, column=0)
last_miles_entry.grid(row=0, column=1)
#tab2 widgets
miles_label = ttk.Label(tab2, text= "Enter your cars current mileage:")
miles_entry = ttk.Entry(tab2, width=7)
miles_button = ttk.Button(tab2, text="Enter", command=check_oil_change)
output_label = ttk.Label(tab2, text="")
maintenance_choices = [ #drop down menu options
"Oil change",
"Tire Rotation",
"Spark Plugs",
]
clicked = StringVar()
clicked.set( "Oil" )
maintenance_choices_dropdown = OptionMenu(tab2, clicked, *maintenance_choices, command = OptionMenu_SelectionEvent)
#tab2 positioning
maintenance_choices_dropdown.grid(row=0, column=0, sticky="W")
miles_label.grid(row=1, column=0)
miles_entry.grid(row=1, column=1)
miles_button.grid(row=1, column=2)
output_label.grid(row=2, column=1)
root.mainloop()
Related
In this code. I want display the information from the frame I hit the Buy button on. I'm sure it is a simple solution but it has eluded me. I've been going through google and stack overflow with no solution yet.
I tried making the NewFrame global but that just does the last one made.
from tkinter import *
root = Tk()
FrameNum = 1
ItemCount = 1
def combine_funcs(*funcs):
def combined_func(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combined_func
def place_order():
global ItemCount
Product = Product_Box.get()
Label(root, text="Your Purchase of " + str(Product) + " Placed").grid(row=1, column=3, stick="w")
ItemCount += 1
def create_frame():
global FrameNum
NewFrame = LabelFrame(root,name=("newframe"+str(FrameNum)), text=("Item "+str(FrameNum)),width=100, height=100)
NewFrame.grid(row=FrameNum, column=0)
Product_Lab = Label(NewFrame, text="Product").grid(row=0, column=0)
Qty_Lab = Label(NewFrame, text="Qty").grid(row=0, column=1)
Price_Lab = Label(NewFrame, text="Price").grid(row=0, column=2)
# Entry Boxes
Product_Box = Entry(NewFrame, width=10).grid(row=1, column=0)
Qty_Box = Entry(NewFrame, width=12).grid(row=1, column=1)
Price_box = Entry(NewFrame, width=6).grid(row=1, column=2)
Remove_Bet_Button = Button(NewFrame, text="Del", command=NewFrame.destroy).grid(row=3, column=2)
Buy_Button = Button(NewFrame, text="Buy", command=combine_funcs(place_order, NewFrame.destroy)).grid(row=3, column=0)
FrameNum += 1
framebutton = Button(root, text="Frame", command=create_frame).grid(row=0, column = 3, stick ="n")
root.mainloop()
I get this error when hitting the Buy button. (with or without information entered into the boxes from that frame)
NameError: name 'Product_Box' is not defined
Product_Box is local variable created in create_frame() - to access it in other functions you have to assign to global variable - so you need add global Product_Box in create_frame()
But there is other problem:
variable = tk.Widget().grid() assigns None to variable because grid()/pack()/place() returns None. You have to do it in two steps variable = tk.Widget() and varaible.grid().
Product_Lab = Label(NewFrame, text="Product")
Product_Lab.grid(row=0, column=0)
And now code works but later you will have the same problem with other variables.
Full working code with other changes
PEP 8 -- Style Guide for Python Code
import tkinter as tk # PEP8: `import *` is not preferred
# --- functions ---
def place_order(product_box, qty_box, price_box, new_frame):
global item_count
global label
product = product_box.get()
qty = int(qty_box.get())
price = int(price_box.get())
total = qty * price
if not label:
label = tk.Label(root)
label.grid(row=1, column=3, stick="w")
# replace text
#label['text'] = f"Your Purchase of {product} Placed. (Qty: {qty}, Price: {price}, Total: {total})"
# or append in new line
if len(label['text']) > 0:
label['text'] += "\n"
label['text'] += f"Your Purchase of {product} Placed. (Qty: {qty}, Price: {price}, Total: {total})"
item_count += 1
new_frame.destroy()
def create_frame():
global frame_number
new_frame = tk.LabelFrame(root, name=f"newframe {frame_number}", text=f"Item {frame_number}", width=100, height=100)
new_frame.grid(row=frame_number, column=0)
tk.Label(new_frame, text="Product").grid(row=0, column=0)
tk.Label(new_frame, text="Qty").grid(row=0, column=1)
tk.Label(new_frame, text="Price").grid(row=0, column=2)
# Entry Boxes
product_box = tk.Entry(new_frame, width=10)
product_box.grid(row=1, column=0)
qty_box = tk.Entry(new_frame, width=12)
qty_box.grid(row=1, column=1)
price_box = tk.Entry(new_frame, width=6)
price_box.grid(row=1, column=2)
tk.Button(new_frame, text="Del", command=new_frame.destroy).grid(row=3, column=2)
tk.Button(new_frame, text="Buy", command=lambda:place_order(product_box, qty_box, price_box, new_frame)).grid(row=3, column=0)
frame_number += 1
# --- main ---
frame_number = 1
item_count = 1
root = tk.Tk()
tk.Button(root, text="Frame", command=create_frame).grid(row=0, column=3, stick="n")
label = None # it will add later but only once
root.mainloop()
So I'm trying to create a tkinter GUI and I want an entry widget to appear in one location if 'Yes' is selected on a list, and then an alternate location if 'No' is selected. I am also having a problem with clearing my entry boxes and removing the widgets that appear when 'Yes' is selected. It is supposed to be a interest collecting form that writes info input by the user to send an email to them after directing them to other resources and such. Is there an alternate way I should go about handling the logic other than if statements? I am relatively new to python and I got to this point and I don't know how to solve it.
import pandas as pd
from openpyxl import load_workbook
from tkinter import *
import tkinter as tk
import shutil
from PIL import Image, ImageTk
from tkinter import font
writer = pd.ExcelWriter('1511Application.xlsx', engine='xlsxwriter')
#writing bulk data
df = pd.DataFrame({'Name': [''], 'Email': [''], 'Subject': [''], 'Message': [''], 'Grade': [''], 'Mechanical': [''], 'Electrical': [''], 'Marketing': [''], 'Graphic Design': [''], 'Programming': [''], 'Chairmans': ['']})
df.to_excel(writer, sheet_name='Sheet1', index=False)
writer.save()
root = Tk()
root.title('FIRST team 1511 - Rolling Thunder Student Interest Form')
root.iconbitmap('1511Icon.ico')
root.geometry("800x500+0+0")
photo = PhotoImage(file="1511logo3.png")
teamlogo = Label(root, image=photo)
Titlefont = font.Font(family='Helvetica', size=14, weight='bold')
font.families()
tk.Label(root, text="FIRST Team 1511 - Rolling Thunder \n Student Interest form", font=Titlefont).place(x=150, y=20)
tk.Label(root, text="Name:", bg='red3', fg='black', width=25,height=1).place(x=130, y=80)
tk.Label(root, text="Email:", bg='red3', fg='black', width=25, height=1).place(x=130,y=110)
tk.Label(root, text="Have you been in FIRST before?", bg='red3', fg='black', width=25, height=1).place(x=130,y=170)
tk.Label(root, text="Grade:", bg="red3", fg='black', width=25, height=1).place(x=130,y=140)
interest_label = tk.Label(root, text="What are you most interested in?", bg="red3", fg="black", width=25, height=1)
interest_label.place(x=130,y=200)
#dropdown event handling
def selected(event):
global other_expand_failsafe2
entrydisplay = clicked.get()
if 'Yes' in entrydisplay:
global extrainfo
extrainfo = tk.Entry(root, width=32)
extrainfo.place(x=312,y=201)
extra_label = tk.Label(root, text='If yes, what team and level of FIRST?', width=28, height=1, bg='red3', fg='black')
extra_label.place(x=110, y=200)
interest_label.place(x=130,y=230)
interest_mechanical.place(x=311, y=228)
interest_electrical.place(x=311, y=248)
interest_marketing.place(x=311, y=268)
interest_design.place(x=311, y=288)
interest_programming.place(x=311, y=308)
interest_chairmans.place(x=311, y=328)
interest_advocacy.place(x=311, y=348)
interest_leadership.place(x=311, y=368)
interest_video_production.place(x=311, y=388)
interest_social_media.place(x=311, y=408)
other_checkbox.place(x=311, y=428)
extrainfo_on = "1"
else:
#This is for when "No" is selected and Other is checked
other_expand_failsafe = "1"
extrainfo_on = "0"
#entrybox next to other checkbox
def expand():
other.set("1")
other_expand = other.get() #other=1 basically
global other_entry
global other_entry1
if "1" in other_expand:
other_entry = tk.Entry(root, width=30)
other_entry.place(x=371, y=430)
if "1" in other_expand and other_expand_failsafe:
other_entry.place(x=371, y=430)
def OtherClear():
if '0' in other_expand_failsafe2:
other_entry.place(x=798, y=400)
def ExtraInfoClear():
if "1" in extrainfo_on:
extrainfo.place(x=312,y=201)
extra_label.place(x=110, y=200)
else:
pass
def Submit():
df = pd.DataFrame({'Name': [f"{name.get()}"], 'Email': [f"{email.get()}"], 'Subject': ['Thanks for coming to our event!'], 'Message': ['Test'], 'Grade': [f"{int(grade.get())}"], 'Mechanical': [f"{mechanical.get()}"], 'Electrical': [f"{electrical.get()}"], 'Marketing': [f"{marketing.get()}"], 'Graphic Design': [f"{design.get()}"], 'Programming': [f"{programming.get()}"], 'Chairmans': [f"{chairmans.get()}"]})
writer = pd.ExcelWriter('1511Application.xlsx', engine='openpyxl')
writer.book = load_workbook('1511Application.xlsx')
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
reader = pd.read_excel(r'1511Application.xlsx')
df.to_excel(writer, index=False, header=False, startrow=len(reader)+1)
writer.close()
name.delete(0, END)
email.delete(0, END)
FIRST.delete(0, END)
grade.delete(0,END)
extrainfo.delete(0,END)
interest_mechanical.deselect()
interest_electrical.deselect()
interest_marketing.deselect()
interest_design.deselect()
interest_programming.deselect()
interest_chairmans.deselect()
interest_advocacy.deselect()
interest_leadership.deselect()
interest_social_media.deselect()
interest_video_production.deselect()
other_checkbox.deselect()
#set failsafe2 to 0 to hide entry box
other_expand_failsafe2 = "0"
OtherClear()
ExtraInfoClear()
def Clear():
name.delete(0, END)
email.delete(0, END)
clicked.set(options[1])
grade.delete(0, END)
interest_mechanical.deselect()
interest_electrical.deselect()
interest_marketing.deselect()
interest_design.deselect()
interest_programming.deselect()
interest_chairmans.deselect()
interest_advocacy.deselect()
interest_leadership.deselect()
interest_social_media.deselect()
interest_video_production.deselect()
other_checkbox.deselect()
extrainfo.delete(0, END)
other_entry.delete(0,END)
#set failsafe2 to 0 to hide entry box
other_expand_failsafe2 = "0"
OtherClear()
submit_button = tk.Button(root, text="Submit", width=10, command=Submit, padx=10, pady=10, bg='red3', fg='black')
submit_button.place(x=20, y=450)
clear_button = tk.Button(root, text="Clear Form", width=10, command=Clear, padx=12, pady=10, bg='red3', fg='black')
clear_button.place(x=570, y=450)
info = StringVar()
name = tk.Entry(root, width=30, textvariable=info)
name.place(x=311,y=81)
email = tk.Entry(root, width=30)
email.place(x=311,y=111)
#DROPDOWN BASE CODE
options = [
'Yes',
'No'
]
clicked = StringVar()
clicked.set(options[1])
#ENDS ABOVE
FIRST = tk.OptionMenu(root, clicked, *options, command=selected)
FIRST.place(x=311, y=165)
grade = tk.Entry(root, width=30)
grade.place(x=311, y=140)
mechanical = IntVar()
electrical = IntVar()
marketing = IntVar()
design = IntVar()
programming = IntVar()
chairmans= IntVar()
advocacy = IntVar()
leadership = IntVar()
video_production = IntVar()
social_media = IntVar()
other = StringVar()
other.set("0")
interest_mechanical = tk.Checkbutton(root, text="Mechanical", variable=mechanical)
interest_electrical = tk.Checkbutton(root, text="Electrical", variable=electrical)
interest_marketing = tk.Checkbutton(root, text="Marketing", variable=marketing)
interest_design = tk.Checkbutton(root, text="Graphic Design", variable=design)
interest_programming = tk.Checkbutton(root, text="Programming", variable=programming)
interest_chairmans = tk.Checkbutton(root, text="Public Speaking/Chairmans", variable=chairmans)
interest_advocacy = tk.Checkbutton(root, text='Government Advocacy', variable=advocacy)
interest_leadership = tk.Checkbutton(root, text='Leadership', variable=leadership)
interest_video_production = tk.Checkbutton(root, text='Video Production', variable=video_production)
interest_social_media = tk.Checkbutton(root,text='Social Media', variable=social_media)
other_checkbox = tk.Checkbutton(root, text='Other', variable=other, command=expand)
interest_mechanical.place(x=311, y=198)
interest_electrical.place(x=311, y=218)
interest_marketing.place(x=311, y=238)
interest_design.place(x=311, y=258)
interest_programming.place(x=311, y=278)
interest_chairmans.place(x=311, y=298)
interest_advocacy.place(x=311, y=318)
interest_leadership.place(x=311, y=338)
interest_video_production.place(x=311, y=358)
interest_social_media.place(x=311, y=378)
other_checkbox.place(x=311, y=398)
teamlogo.place(x=520, y=20)
root.mainloop()
I am trying to print a corresponding value to the index of a list from another list like so:
print(safeDis[chem.index(self.drop2)])
but when doing this i get the above error. I believe i had this working in a previous iteration but i cannot find the one that was.
import tkinter as tk
from tkinter import ttk
safeDis = [4,88,18,50,12,100]
chem = ["HTP 50%","HTP 84%","HTP 90%","Kerosene","Benzene"]
class Page4:
def __init__(self,root):
self.root = root
self.toplbl = ttk.Label(root, text="Select firing point meterials ",font=("arial",12)) #lable for select meterial 1
self.lbl1 = ttk.Label(root, text="Meterial 1: ",font=("arial",10)) #lable for select meterial 1
self.lbl2 = ttk.Label(root, text = "Meterial 2: " ,font = ("arial",10)) #lable for meterial 2
self.masslbl = ttk.Label(root, text="Mass in Kg:",font=("arial",10))
self.masslbl2 = ttk.Label(root, text="Mass in Kg:",font=("arial",10))
self.typelbl = ttk.Label(root, text="Type:",font=("arial",10))
self.typelbl2 = ttk.Label(root, text="Type:",font=("arial",10))
self.Apply = ttk.Button(root, text="Apply", command = self.new_window) #button to confirm the meterial choices
self.Back = ttk.Button(root, text="Back", command = print("DONG"))
self.mass1 = ttk.Entry(root, width=8)
self.mass2 = tk.Entry(root,width=8)
self.clicked = tk.StringVar() #set the variable to a string value allowing the meterial names to apeer in it
self.clicked.set(chem[3]) #set the default meterial from the chem list
self.clicked2 = tk.StringVar()
self.clicked2.set(chem[3])
self.drop2 = tk.OptionMenu(root, self.clicked2, *chem) #setup the dropdown menue with optionmenue function set to the chem list
self.drop = tk.OptionMenu(root, self.clicked, *chem)
self.toplbl.grid(column=0, row=0,columnspan=3,sticky="w",padx=10,pady=10) #place meterial label 1
self.lbl1.grid(column=0, row=1,padx=10) #place meterial label 1
self.lbl2.grid(column=0, row=3,padx=10) #place meterial label 2
self.mass1.grid(column=2, row=2)
self.mass2.grid(column=2, row=4)
self.masslbl.grid(column=1, row=2)
self.masslbl2.grid(column=1, row=4)
self.typelbl.grid(column=1, row=1,sticky="w")
self.typelbl2.grid(column=1, row=3,sticky="w")
self.drop.grid(column=2, row=1) #place the dropdown menue
self.drop2.grid(column=2, row=3)
self.Apply.grid(column=2,row=5,pady=10,padx=10)
self.Back.grid(column=1,row=5,pady=10,padx=10)
print(safeDis[chem.index(self.drop2)])
def new_window(self):
#print(dongalong)
for widget in self.root.winfo_children():
widget.destroy()
self.app = Page3(self.root)
#class Page5:
def main():
root = tk.Tk()
app = Page4(root)
root.mainloop()
if __name__ == '__main__':
main()
The problem was that self.drop2 is an object of OptionMenu, not the value of it. To get the value returned by it, use the get() method on its variable defined (self.clicked2.get())
So it should be:
print(safeDis[chem.index(self.clicked2.get())])
Hope it solved the error, do let me know if any more doubts
Cheers
I am new to tkinter Python module and creating a very simple UI with tkinter.
Its basically a optical card which will first ask for card number. User can enter "Card1 or Card2". For Card1 there is one more edit which ask for KM range like 10KM, 40KM, 80KM and user can enter the value specified and it gives the optimal value and acceptable value.
Code is working fine. Only problem is with clearing the information using clear button for Card1. I am not able to clear the complete information for Card1 which includes clearing the edit box and outout.
Below is the code
from tkinter import *
from tkinter import ttk
import tkinter
frm = Tk()
frm.geometry('600x400')
frm.title("Optical Power Specs")
bg = "#94FB9E"
fnt = 'tahoma 15 bold'
frm.config(bg=bg)
frm.resizable(False, False)
#frm.iconbitmap('f.gif')
frame = Frame(frm, bg=bg)
frame2 = Frame(frm, bg=bg)
frame4 = Frame(frm, bg=bg)
def f():
global lbl104080
global frame3
global txt104080
if str(txt1.get()) == 'Card1':
print("entered ehre")
frame3 = Frame(frm, bg=bg)
frame3.grid(row=3, column=0)
txt104080 = Entry(frame3, textvariable=sv104080)
lbl104080 = Label(frame3, text="Enter 10KM or 40KM or 80KM ", font='None 10', background=bg, padx=0)
lbl104080.grid(row=1, column=0, pady=30)
txt104080.grid(row=1, column=1)
if str(txt104080.get()) == '10KM':
lblr['text'] = ("""
Optimal Value = -10 To -10 dBm
Acceptable Value = -10 To -10 dBm
""")
elif str(txt104080.get()) == '40KM':
lblr['text'] = ("""
Optimal Value = -40 To -40 dBm
Acceptable Value = -40 To 40 dBm
""")
elif str(txt1.get()) == 'Card2':
lblr['text'] = ("""
Optimal Value = -2 To -2 dBm
Acceptable Value = -2 To -2 dBm
""")
elif str(txt1.get()) == 'A1236':
lblr['text'] = ("""
Optimal Value = -100 To -20 dBm
Acceptable Value = -3 To 1 dBm
""")
def clea():
# global lbl104080
#lbl104080['text'] = ('')
txt104080['text'] = ('')
lbl104080.destroy()
frame3.grid_forget()
frame3.destroy()
#frame3.destroy()
lblr['text'] = ('')
sv104080 = StringVar()
opt = ttk.Label(frm, text='Optical Power Specs', font=fnt, background=bg)
Ent = ttk.Label(frame, text='Enter BOM Code OR Card Name', font='None 10', background=bg)
btnok = ttk.Button(frame2, text='OK', command=f)
btncancel = ttk.Button(frame2, text='Clear', command=clea)
lblr = ttk.Label(frame4, font='None 10', background=bg)
svname_bom = StringVar()
txt1 = Entry(frame, textvariable=svname_bom)
opt.grid(row=0, column=0, pady=5, padx=200)
frame.grid(row=1, column=0)
Ent.grid(row=0, column=0, padx=10, pady=20)
txt1.grid(row=0, column=1)
frame2.grid(row=2, column=0)
btnok.grid(row=0, column=0, padx=10, pady=20)
btncancel.grid(row=0, column=1, pady=20)
frame4.grid(row=4, column=0)
lblr.grid(row=2, column=0, pady=50, padx=100)
frm.mainloop()
Please help me to solve this issue
You probably want txt1.delete(0, 'end') that will delete all text from main entry text
def clea():
#lbl104080['text'] = ('')
txt104080['text'] = ('')
txt1.delete(0, 'end')
lbl104080.destroy()
frame3.grid_forget()
frame3.destroy()
#frame3.destroy()
lblr['text'] = ('')
I wrote a python program with tkinter to reveal the continent of each these 4 countries: Nigeria, Canada, China, and Australia -- when the user clicks an "enter" button. I want when the user clicks the "Enter" button, then the text in the response label should reveal the particular continent the selected country belongs to.
The main issue is that I don't know how to make the output to update in a label visible in the main program window, instead the output is displayed on python shell. (I'm a novice in python tkinter GUI)
============================ The Code =====================================
from functools import partial
import tkinter as tk
from tkinter import *
def serial_port(var):
selection = var.get()
# to save space
text_dict = {
1: 'Africa',
2: 'North America',
3: 'Asia',
4: 'Australia'}
text_to_print = text_dict[selection]
print(text_to_print) #apparently, I learn I can't use print in GUI but idk what to use in place of print here
def main():
root= tk.Tk()
root.title("Continent")
root.geometry("500x300")
var = IntVar()
var.set(1)
#Button to show selected profile to assign FTW
Lang_1=Radiobutton(root, text='Nigeria', variable=var, value=1, width=20)
Lang_2=Radiobutton(root, text='Canada', variable=var, value=2, width=20)
Lang_3=Radiobutton(root, text='Japan', variable=var, value=3, width=20)
Lang_4=Radiobutton(root, text='Australia', variable=var, value=4, width=20)
# Button to show entered reg values and data in it
Enter_Button=Button(root, text='ENTER',command=partial(serial_port, var), relief="ridge", background="Cyan", width=20)
Lang_1.grid(row=1, column=5)
Lang_2.grid(row=2, column=5)
Lang_3.grid(row=3, column=5)
Lang_4.grid(row=4, column=5)
Enter_Button.grid(row=7, column=3)
root.mainloop()
if __name__ == '__main__':
main
To print text into a tkinter GUI, you need a separate label widget.
Check the code below. I have added the widget Return_Label, which you can change the config and position of to however you like. I'm pretty sure this should do what you want.
#These variables are made global so both functions can access them
var = None
Return_Label = None
def serial_port():
global var, Return_Label
selection = var.get()
text_dict = {
1: "Africa",
2: "North America",
3: "Asia",
4: "Australia"}
text_to_print = text_dict[selection]
Return_Label.config(text = text_to_print)
def main():
global var, Return_Label
root = tk.Tk()
root.title("Continent")
root.geometry("500x300")
var = tk.IntVar()
var.set(1)
Lang_1 = tk.Radiobutton(root, text = "Nigeria", variable = var, value = 1, width = 20)
Lang_2 = tk.Radiobutton(root, text = "Canada", variable = var, value = 2, width = 20)
Lang_3 = tk.Radiobutton(root, text = "Japan", variable = var, value = 3, width = 20)
Lang_4 = tk.Radiobutton(root, text = "Australia", variable = var, value = 4, width = 20)
Enter_Button = tk.Button(root, text = "ENTER", command = serial_port, relief = "ridge", bg = "Cyan", width = 20)
Return_Label = tk.Label(root)
Lang_1.grid(row = 1, column = 5)
Lang_2.grid(row = 2, column = 5)
Lang_3.grid(row = 3, column = 5)
Lang_4.grid(row = 4, column = 5)
Enter_Button.grid(row = 7, column = 3)
Return_Label.grid(row = 6, column = 3) #change this to wherever you want it printed
root.mainloop()
if (__name__ == "__main__"):
main()
You're almost there. You need to use an Entry widget.
from functools import partial
import tkinter as tk
from tkinter import *
def serial_port(var,entry): #add the Entry widget as variable
entry.delete(0, 'end') #clear the entry
selection = var.get()
text_dict = {
1: 'Africa',
2: 'North America',
3: 'Asia',
4: 'Australia'}
text_to_print = text_dict[selection]
entry.insert(0,text_to_print) #set the entry
def main():
root= tk.Tk()
root.title("Continent")
root.geometry("500x300")
var = IntVar()
var.set(1)
entry = Entry() #create the Entry widget
Lang_1=Radiobutton(root, text='Nigeria', variable=var, value=1, width=20)
Lang_2=Radiobutton(root, text='Canada', variable=var, value=2, width=20)
Lang_3=Radiobutton(root, text='Japan', variable=var, value=3, width=20)
Lang_4=Radiobutton(root, text='Australia', variable=var, value=4, width=20)
Enter_Button=Button(root, text='ENTER',command=partial(serial_port, var, entry), relief="ridge", background="Cyan", width=20) #pass the Entry widget
Lang_1.grid(row=1, column=5)
Lang_2.grid(row=2, column=5)
Lang_3.grid(row=3, column=5)
Lang_4.grid(row=4, column=5)
Enter_Button.grid(row=7, column=3)
entry.grid(row=8, column=3) #place the Entry widget
root.mainloop()
if __name__ == '__main__':
main()
use the Label() function. It takes the parent widget, and the text.
Label(parent, text = "what you want").