python_by_example/tkgui/tk12.py
2023-11-19 02:49:30 -03:00

58 lines
1.8 KiB
Python

from os import getcwd as pwd
import tkinter as tk
def tk_12():
"""Create a simple program that shows a drop-down list containing several
colours and a Click Me button. When the user selects a colour from the list
and clicks the button it should change the background of the window to that
colour. For an extra challenge, try to avoid using an if statement to do this."""
base_path = f"{pwd()}/tkgui/imgs"
window = tk.Tk()
window.title("Colores TK")
window.geometry("380x400")
title_icon = tk.PhotoImage(file = f"{base_path}/devfzn_64x64.png")
window.iconphoto(False, title_icon)
window["bg"] = "white"
colours = [
'dark slate gray',
'slate gray',
'cornflower blue',
'dodger blue',
'deep sky blue',
'dark turquoise',
'pale goldenrod',
'tomato',
'violet red',
'purple',
'DarkOrchid2',
'DarkOrchid4',
]
lbl_info = tk.Label(text="COLORES", font="Verdana 50")
lbl_info["bg"] = "white"
lbl_info.place(x=40, y=25, width=300, height=75)
lst_color = tk.Listbox()
for i, color in enumerate(colours):
lst_color.insert(i, color)
lst_color["justify"] = "center"
lst_color.place(x=40, y=160, width=300, height=220)
def apply_color():
try:
color = lst_color.curselection()[0]
window["bg"] = colours[color]
lbl_info["bg"] = colours[color]
except IndexError:
window["bg"] = "white"
lbl_info["bg"] = "white"
lst_color.focus()
btn_chng_color = tk.Button(text="Aplicar Color", command=apply_color)
btn_chng_color.place(x=40, y=110, width=300, height=35)
btn_chng_color.focus()
window.mainloop()