[Python]Updating the GUI depending on the dropdown menu option - python

I am creating a simple temperature converter in python using tkinter. I have created a drop down menu with the options and a convert button. What I want to do is when the dropdown menu's changes I want the button to do a different thing. How can I achieve this ?
(example in this case: if celcius to fahrenheit is chosen button should convert cel to fahrenheit if fahr to celsius is chosen it should convert that way. )
Here is the code:
from tkinter import *
def converter():
# Create functions for conversion
def cel_fahr():
res = int(entry.get()) * 9/5 +32
print (res)
def fahr_cel():
res = (int(entry.get()) - 32) * 5/9
print (res)
#Options list for the dropdown
list_opt = ['Celsius to Fahrenheit', 'Fahrenheit to Celsius']
# Create the main window
root = Tk()
# Rename the title of the window
root.title("Temperature Converter")
# Set the size of the window
root.geometry("250x250")
# Set resizable FALSE
root.resizable(0,0)
# Create a variable for the default dropdown option
var1 = StringVar()
# Set the default drop down option
var1.set(list_opt[0])
# Create the dropdown menu
dropdown = OptionMenu(root, var1, *list_opt)
dropdown.configure(state="active")
# Place the dropdown menu
dropdown.place(x=45, y=10)
# Create an entry
entry = Entry(root)
entry.place (x=47, y=60)
#Create a button
button = Button(root, text='Convert', command=cel_fahr)
button.place(x=85,y=90)
#I TRIED THIS BUT NO
#if var1 == list_opt[0]:
#button = Button(root, text='Convert', command=cel_fahr)
#button.place(x=85,y=90)
#if var1 == list_opt[1]:
#button = Button(root, text='Convert', command=fahr_cel)
#button.place(x=85,y=90)
root.mainloop()
converter()

Switched up your code a little bit:
from tkinter import *
def converter():
# Create functions for conversion
def cel_fahr():
res = int(entry.get()) * 9/5 +32
print (res)
def fahr_cel():
res = (int(entry.get()) - 32) * 5/9
print (res)
def convert():
if selected.get() == 'Celsius to Fahrenheit':
cel_fahr()
else:
fahr_cel()
#Options list for the dropdown
list_opt = ['Celsius to Fahrenheit', 'Fahrenheit to Celsius']
# Create the main window
root = Tk()
# Rename the title of the window
root.title("Temperature Converter")
# Set the size of the window
root.geometry("250x250")
# Set resizable FALSE
root.resizable(0,0)
# Create a variable for the default dropdown option
selected = StringVar(root)
# Set the default drop down option
selected.set('Celsius to Fahrenheit')
# Create the dropdown menu
dropdown = OptionMenu(root, selected, 'Celsius to Fahrenheit', 'Fahrenheit to Celsius')
# Place the dropdown menu
dropdown.place(x=45, y=10)
# Create an entry
entry = Entry(root)
entry.place (x=47, y=60)
#Create a button
button = Button(root, text='Convert', command=convert)
button.place(x=85,y=90)
root.mainloop()
converter()
Instead of the options being in a list, I've just dropped them into the menu when it's created. When the button is pressed, it then calls a function which decides which conversion to use, based on the value selected in the dropdown menu.
I've also changed the variable name for var1 (to "selected"), because it's not very descriptive, and got a bit confusing to code with.

Related

How to display the label ( text) value dynamically based on combo box selection value ( List box) in Tkinter?

I am new to tkinter application. The below code is working fine. Please help how to implement mentioned features.
The dynamic value should be displayed above clear button or below the combo box ( Used pack is bottom )- Now working
Clear the label value on combo box selection.
import tkinter as tk
from tkinter import ttk
from tkinter import *
from datetime import datetime
# root window
root = tk.Tk()
root.geometry("500x350")
root.resizable(False, False)
root.title('Test')
# Log Generator in frame
Generator = tk.Frame(root)
Generator.pack(padx=10, pady=10, fill='x', expand=True)
def clear():
combo.set('')
# Function to print the index of selected option
# in Combobox
def get_log_file_name(*arg):
date_Value = datetime.now().strftime("%Y_%m_%d_%I%M%S")
output_file_name_value = "Log_"+date_Value
if var.get() == "apple":
Label(Generator, text="The value at index: "+output_file_name_value+".txt", font=('Helvetica 12')).pack()
else:
Label(Generator, text="The value at index: "+output_file_name_value+".html", font=('Helvetica 12')).pack()
# Define Tuple of months
months = ('apple','banana')
# Create a Combobox widget
label = ttk.Label(Generator, text="Selection_Option:",font=('Helvetica', 10, 'bold'))
label.pack(fill='x', expand=True)
var = StringVar()
combo = ttk.Combobox(Generator, textvariable=var)
combo['values'] = months
combo['state'] = 'readonly'
combo.pack(padx=5, pady=5)
# Set the tracing for the given variable
var.trace('w', get_log_file_name)
# Create a button to clear the selected combobox
# text value
button = Button(Generator, text="Clear", command=clear)
button.pack(side=left)
# Make infinite loop for displaying app on
# the screen
Generator.mainloop()
Clear the label value on combo box selection.
You need to capture the ComboboxSelect event to do that and the function to execute if captured
the function should be like this
What you want to do here, is to capture the combobox event, and then, do the label configuration when capturing it,
Below is the code to do the thing. and you can add code there.
def comboboxEventCapture(e=None):
label.configure(text='')
# Your code after resetting variables!
Here's the event capturing part
combo.bind("<<ComboboxSelect>>", comboboxEventCapture)
You can name the function whatever you want though.
Note that the arguement e is needed because if the event is captured, the event itself is passed as a parameter into the function, that is of no use here (unless you are going to do something with it, then use e.objname)
The dynamic value should be displayed above clear button
The second label could be outside of get_log_file_name() function.
And also configure inside function. So you don't do duplicate Label widget, naming Label2
Also the pack() must be split to prevent an error.
To clear Label2 use .configure(text='')
We will be using ttk. So don't do this from tkinter import *
Code:
import tkinter as tk
from tkinter import ttk
from datetime import datetime
root = tk.Tk()
root.geometry("500x350")
root.resizable(False, False)
root.title('Test')
Generator = tk.Frame(root)
Generator.pack(padx=10, pady=10, fill='x', expand=True)
def clear():
label2.configure(text='')
def get_log_file_name(*arg):
date_Value = datetime.now().strftime("%Y_%m_%d_%I%M%S")
output_file_name_value = "Log_"+date_Value
if var.get() == "apple":
label2.configure(text="The value at index: "+output_file_name_value+".txt", font=('Helvetica 12'))
else:
label2.configure(text="The value at index: "+output_file_name_value+".html", font=('Helvetica 12'))
# Define Tuple of months
months = ('apple','banana')
# Create a Combobox widget
label2 = ttk.Label(Generator)
label2.pack()
label = ttk.Label(Generator, text="Selection_Option:",font=('Helvetica', 10, 'bold'))
label.pack(fill='x', expand=True)
var = tk.StringVar()
combo = ttk.Combobox(Generator, textvariable=var)
combo['values'] = months
combo['state'] = 'readonly'
combo.pack(padx=5, pady=5)
# Set the tracing for the given variable
var.trace('w', get_log_file_name)
# Create a button to clear the selected combobox
# text value
button = ttk.Button(Generator, text="Clear", command=clear)
button.pack(side='left')
# Make infinite loop for displaying app on
# the screen
Generator.mainloop()
Screenshot for apple:
Screenshot for banana:
Screenshot to clear Label2:

How do I include a calculation function in a menu item in Tkinter?

I created a menu item and want to run a function within that menu which will run a simple calculation based on a entry. When I run the code in my terminal, I can see my window and the menu item with the entry widget. But, I don't see anything and result from my function. I don't get an error from the terminal. Below is my code. Where did I mess in my code?
from tkinter import *
root = Tk()
root.title(" My calculator")
root.geometry("400x400")
# Defining calculator 1 function
def calculator_1():
# creating an entry
frame1.pack(fill="both",expand=1)
e1 =Entry(frame1)
e1.pack(pady=5)
# Defining the formula function
def formula():
res = (int(e1.get()) + 1)
myText.set(res)
# creating a calculate button
my_button = Button(frame1, text="Click to calculate", command=formula)
my_button.pack(pady=5)
myText=StringVar()
result=Label(frame1, text=" your results is ", textvariable =myText)
result.pack(pady=5)
label_result =Label(frame1, text= "Your result is")
label_result.pack(pady=5)
# Define Main menu
my_menu = Menu(root)
root.config(menu=my_menu)
#create menu items
math_menu = Menu(my_menu)
my_menu.add_cascade(label="MathCards",menu=math_menu)
math_menu.add_command(label="Calculator 1",command=calculator_1)
math_menu.add_separator()
math_menu.add_command(label="Exit", command=root.quit)
# Creating a frame
frame1 = Frame(root, width =400, height=400)
root.mainloop()

Update the window with a OptionMenu in tkinter

I am looking for a way to change the content of the window based on what option you select in the OptionMenu. It should have 3 different options, namely "Introduction", "Encrypt" and "Decrypt". I've the code to create an OptionMenu but now I wanna know how can I modify them to show a different page, depending on the one who is selected. Could someone help me with that? I am using python 3
so for example:
from tkinter import *
OptionList = [
"Einführung",
"Verschlüsseln",
"Entschlüsseln"
]
window = Tk()
window.geometry('200x200')
variable = StringVar(window)
variable.set(OptionList[0])
opt = OptionMenu(window, variable, *OptionList)
opt.config(width=90, font=('Calbri', 12))
opt.pack(side="top")
window.mainloop()
This will produce a window with a OptionMenu with the three options I wrote above (just in German) and now I'd like to change the page depending on the current chosen option of the OptionMenu
Thanks guys!
This is now the forth edit or something, but thats the final solution i've come up with.
#coding=utf-
import tkinter as tk
from tkinter import *
window = Tk()
window.geometry('200x200')
OptionList = ["Einführung", "Verschlüsseln", "Entschlüsseln"]
class App:
def __init__(self, master):
self.choice_var = tk.StringVar()
self.choice_var.set(OptionList[0])
opt = OptionMenu(window, self.choice_var, *OptionList, command=self.switch)
opt.config(width=90, font=('Calbri', 12))
opt.pack(side="top")
self.random_label1 = tk.Label(window, text="Welcome content here")
self.random_label2 = tk.Label(window, text="Encrypt content here")
self.random_label3 = tk.Label(window, text="Decrypt content here")
self.random_label1.pack()
self.random_label2.pack()
self.random_label3.pack()
self.label_info1 = self.random_label1.pack_info()
self.label_info2 = self.random_label2.pack_info()
self.label_info3 = self.random_label3.pack_info()
self.switch()
def switch(self, *args):
var = str(self.choice_var.get())
if var == "Einführung":
self.random_label1.pack(self.label_info1)
self.random_label2.pack_forget()
self.random_label3.pack_forget()
if var == "Verschlüsseln":
self.random_label2.pack(self.label_info2)
self.random_label1.pack_forget()
self.random_label3.pack_forget()
if var == "Entschlüsseln":
self.random_label3.pack(self.label_info3)
self.random_label2.pack_forget()
self.random_label1.pack_forget()
myApp = App(window)
window.mainloop()

Using tkinter to create drop down menu?

I'm new to Python, and I am trying to create a GUI that displays a list of characteristics when an item in a drop down menu is selected. I want the text to be displayed under the drop down menu. Here is what I have so far, but all it provides is an empty box:
import tkinter
import tkinter as tk
#creates box
window =tkinter.Tk()
frame= tkinter.Frame(window)
frame.pack()
window.geometry("%dx%d+%d+%d" % (330, 80, 200, 150))
window.title("Breeds and Characteristics")
#data
data=('Abyssinian','American-Bobtail','American-Curl')
Output1 ="Aloof,Intelligent,Diseased"
Output2= "Affectionate,Intelligent,Diseased"
Output3= "Affectionate,Dull,Healthy"
display = Label(window, text="")
#create a dropdown list
p = tkinter.Combobox(window, textvariable=var, values=data)
p.pack()
def chars():
for values in p:
if item == 'Abyssinian':
print (Output1)
elif item == 'American-Bobtail':
print (Output2)
elif item == 'American-Curl':
print (Output3)
#starts dropdown box at first cat
var = tkinter.StringVar()
var.set('Abyssinian')
#updates text
def boxtext():
display.configure(text=(chars))
display.pack()
#button to view characteristics
button = Button(window, text='View Characteristics', command=select)
button.pack(side='left', padx=20, pady=10)
window.mainloop()
The drop down widget is called tkinter.OptionMenu. You would need to make a function that can update the Label and provide that function to the OptionMenu as a callback. Like this:
import tkinter
#creates box
window =tkinter.Tk()
window.geometry("%dx%d+%d+%d" % (330, 80, 200, 150))
window.title("Breeds and Characteristics")
#data
data={
'Abyssinian':"Aloof,Intelligent,Diseased",
'American-Bobtail':"Affectionate,Intelligent,Diseased",
'American-Curl':"Affectionate,Dull,Healthy",
}
#updates text
def boxtext(new_value):
display.config(text = data[new_value])
#create a dropdown list
var = tkinter.StringVar()
var.set('Abyssinian')
p = tkinter.OptionMenu(window, var, *data, command=boxtext)
p.pack()
display = tkinter.Label(window)
display.pack()
window.mainloop()

Update label of tkinter menubar item?

Is it possible to change the label of an item in a menu with tkinter?
In the following example, I'd like to change it from "An example item" (in the "File" menu) to a different value.
from tkinter import *
root = Tk()
menu_bar = Menu(root)
file_menu = Menu(menu_bar, tearoff=False)
file_menu.add_command(label="An example item", command=lambda: print('clicked!'))
menu_bar.add_cascade(label="File", menu=file_menu)
root.config(menu=menu_bar)
root.mainloop()
I found the solution myself in the Tcl manpages:
Use the entryconfigure() method like so, which changes the value after it has been clicked:
The first parameter 1 has to be the index of the item you want to change, starting from 1.
from tkinter import *
root = Tk()
menu_bar = Menu(root)
def clicked(menu):
menu.entryconfigure(1, label="Clicked!")
file_menu = Menu(menu_bar, tearoff=False)
file_menu.add_command(label="An example item", command=lambda: clicked(file_menu))
menu_bar.add_cascade(label="File", menu=file_menu)
root.config(menu=menu_bar)
root.mainloop()
I do not know if that used to be different on 2.7, but it does not work on 3.4 anymore.
On python 3.4 you should start counting entries with 0 and use entryconfig.
menu.entryconfig(0, label = "Clicked!")
http://effbot.org/tkinterbook/menu.htm
Check this dynamic menu example. The main feature here is that you don't need to care about a serial number (index) of your menu item. No index (place) of your menu is needed to track. Menu item could be the first or the last, it doesn't matter. So you could add new menus without index tracking (position) of your menus.
The code is on Python 3.6.
# Using lambda keyword and refresh function to create a dynamic menu.
import tkinter as tk
def show(x):
""" Show your choice """
global label
new_label = 'Choice is: ' + x
menubar.entryconfigure(label, label=new_label) # change menu text
label = new_label # update menu label to find it next time
choice.set(x)
def refresh():
""" Refresh menu contents """
global label, l
if l[0] == 'one':
l = ['four', 'five', 'six', 'seven']
else:
l = ['one', 'two', 'three']
choice.set('')
menu.delete(0, 'end') # delete previous contents of the menu
menubar.entryconfigure(label, label=const_str) # change menu text
label = const_str # update menu label to find it next time
for i in l:
menu.add_command(label=i, command=lambda x=i: show(x))
root = tk.Tk()
# Set some variables
choice = tk.StringVar()
const_str = 'Choice'
label = const_str
l = ['dummy']
# Create some widgets
menubar = tk.Menu(root)
root.configure(menu=menubar)
menu = tk.Menu(menubar, tearoff=False)
menubar.add_cascade(label=label, menu=menu)
b = tk.Button(root, text='Refresh menu', command=refresh)
b.pack()
b.invoke()
tk.Label(root, textvariable=choice).pack()
root.mainloop()

Categories