This is my first time using CustomKinter to make a simple GUI. I am trying to get the value of a customtkinter label to change depending on the value selected by the combobox. The textvariable for the output should change for the values in the calculate_output function; the output label is not changing.
from tkinter import StringVar
import customtkinter as ctk
root = ctk.CTk()
root.title("Window")
root.geometry("400x300")
label_1 = ctk.CTkLabel(root, text="Value:", font=("Frutiger", 21))
label_1.place(x=100, y=100)
values = ["80", "150", "180", "250"]
drop_down = ctk.CTkComboBox(root, values=values, border_color="#0072CE", font=("Frutiger", 21),
button_color="#005EB8")
drop_down.place(x=220, y=100)
output_var = StringVar()
label_2 = ctk.CTkLabel(root, text="Output:", font=("Frutiger", 21))
label_2.place(x=100, y=200)
output = ctk.CTkLabel(root, font=("Frutiger", 21), textvariable=output_var)
output.place(x=200, y=200)
def calculate_output(event):
drop_value = drop_down.get()
try:
if drop_value == "80":
output_var.set("None")
elif drop_value == "150":
output_var.set("Aluminium")
elif drop_value == "180":
output_var.set("Copper")
elif drop_value == "250":
output_var.set("Tin")
except ValueError:
output_var.set("Invalid input")
drop_down.bind("<<ComboboxSelected>>", calculate_output)
root.mainloop()
I tried editting the function and binding but I have no idea where the issue is. Help would be appreciated.
You can use the command
parameter of the CTkComboBox
to link it to your function as such:
drop_down = ctk.CTkComboBox(root, values=values, border_color="#0072CE", font=("Frutiger", 21), button_color="#005EB8", command=calculate_output)
That way the function will be executed every time you select a new value. Also make sure to define the function before you link it to the combobox. Your final code would look like this:
from tkinter import StringVar
import customtkinter as ctk
root = ctk.CTk()
root.title("Window")
root.geometry("400x300")
label_1 = ctk.CTkLabel(root, text="Value:", font=("Frutiger", 21))
label_1.place(x=100, y=100)
values = ["80", "150", "180", "250"]
output_var = StringVar()
label_2 = ctk.CTkLabel(root, text="Output:", font=("Frutiger", 21))
label_2.place(x=100, y=200)
output = ctk.CTkLabel(root, font=("Frutiger", 21), textvariable=output_var)
output.place(x=200, y=200)
def calculate_output(event):
drop_value = drop_down.get()
try:
if drop_value == "80":
output_var.set("None")
elif drop_value == "150":
output_var.set("Aluminium")
elif drop_value == "180":
output_var.set("Copper")
elif drop_value == "250":
output_var.set("Tin")
except ValueError:
output_var.set("Invalid input")
drop_down = ctk.CTkComboBox(root, values=values, border_color="#0072CE", font=("Frutiger", 21),
button_color="#005EB8", command=calculate_output)
drop_down.place(x=220, y=100)
root.mainloop()