如何在tkin中用按钮改变标签和背景的颜色

2024-06-16 14:46:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使一个按钮,可以改变背景颜色,随着标签背景色和背景色。我已经创造了一本字典和一本字典的钥匙,无论我做什么,我似乎不能得到它的权利

我试图使用def函数返回一个新的键,但是它不返回它

from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
from random import choice


MAXIMUM_TEMPERATURE = 60
MINIMUM_TEMPERATURE = -100
HOT_TEMPERATURE = 30
COLD_TEMPERATURE = 0
DEFAULT_TOP_TEMPERATURE = "Please input the temperatures first"
DEFAULT_LOCATION = "Please input the locations first"


widget_assist = {"content" : 0, "input_box" : 1, "button" : 2, "combobox" : 3, "heading" : 4}
user_travel_history = {}

class Set_Widgets:
    def __init__(self, widget, text, position, background, pady = (0, 0), padx = (0, 0), font = "Arial", size = 10, width = 10, command = "", values = (), focus = False, type = "default"):
        self._widget = widget
        self._text = text
        self._position = position
        self._pady = pady
        self._padx = padx
        self._font = font
        self._size = size
        self._background = background
        self._width = width
        self._command = command
        self._values = values
        self._focus = focus
        self._type = type
        self._widget_object = None

        if (self._widget == widget_assist["content"]):
            self._widget_object = Label(root, text=self._text, background= self._background, font=(self._font, self._size))
        elif (self._widget == widget_assist["heading"]):
            self._widget_object = Label(root, text=self._text, background= self._background, font=("Helvetica", self._size, 'bold'))
        elif (self._widget == widget_assist["input_box"]):
            self._widget_object = Entry(root, width=self._width)
            if (focus):
                self._widget_object.focus()
        elif (self._widget == widget_assist["button"]):
            self._widget_object = Button(root, text=self._text, command=self._command)
        elif (self._widget == widget_assist["combobox"]):
            self._widget_object = Combobox(root, state="readonly")
            self._widget_object['values'] = values
            self._widget_object.current(0)

        self._widget_object.grid(column=position[0], row=position[1], pady=pady, padx=padx)

    def get_input(self):
        if (self._widget == widget_assist["content"]):
            return self._text
        elif (self._widget == widget_assist["input_box"] or self._widget == widget_assist["combobox"]):
            return self._widget_object.get()

    def change_text(self, text):
        self._widget_object.configure(text=text)


    def delete(self):
        self._widget_object.grid_remove()


class Information:
    def __init__(self, location, temperature):
        self._location = location
        self._temperature = temperature

    def get_location(self):
        return self._location

    def get_temp(self):
        return self._temperature



def converter(value, not_fahrenheit):
    try:
        value = round(float(value), 1)
    except ValueError:
        print("This functions works for only integers")
        return

    if (not_fahrenheit):
       return round(float(str(((value * 9/5) + 32))), 1)
    else:
        return round(float(str(((value - 32) * 5/9))), 1)

def submit(places):
    if (location_input.get_input() == "" or temp_input.get_input() == ""):
        messagebox.showinfo("Please complete all boxes.")
        return
    try:
        temperature = float(temp_input.get_input())
    except ValueError:
        messagebox.showinfo('Please fill the boxes correctly (Use text for temperatures)')
        return

    if (location_input.get_input().isdigit() == True):
        messagebox.showinfo('Please fill the boxes correctly (Use text for locations)')
        return

    default_value = units.get_input()

    if (default_value == "fahrenheit"):
        temperature = converter(temperature, False)

    if (temperature > MAXIMUM_TEMPERATURE):
        messagebox.showinfo("This temperature is over the Max Temperature (Please type something lower than 60 degrees celsius)")
        return
    elif (temperature < MINIMUM_TEMPERATURE):
        messagebox.showinfo("This temperature is under the Min Temperature (Please type a value highter than -100 degrees celsius)")
        return

    travel_information = Information(location_input.get_input(), temperature)
    user_travel_history[travel_information.get_location()] = travel_information

    display = ""
    highest_temp = MINIMUM_TEMPERATURE
    top_temp_location = None

    for key, value in user_travel_history.items():
        display += value.get_location().title() + "\n" + str(value.get_temp()) + " C | " + str(converter(value.get_temp(), True)) + " F" + "\n\n"

        if (value.get_temp() > highest_temp):
            highest_temp = value.get_temp()
            top_temp_location = key



    places.change_text(display)
    top_temp_location_text.change_text(top_temp_location.title() + "\n" + str(highest_temp) + " C | " + str(converter(highest_temp, True)) + " F")

def remove_info():
    user_travel_history.clear()
    places.change_text(DEFAULT_LOCATION)
    top_temp_location_text.change_text(DEFAULT_TOP_TEMPERATURE)

def colorchange():
    colour_variable = "cold"
    return colour_variable

root = Tk()
root.title("Temporature Convertion Program")
root.geometry("360x720")
root.resizable(0,0)
colour = {"default" : "#FFFFFF", "cold" : "#ABD1F3", "hot" : "#CE2029"}
colour_variable = "default"

title = Set_Widgets(widget_assist["heading"], "Temperature Conversion", [0, 0], colour[colour_variable], pady=(10, 0), padx =(3, 0), size=22)
#sub_title = Set_Widgets(widget_assist["content"], "Cool", [0, 1], colour[colour_variable], pady=(10, 10), size=15)

location_text = Set_Widgets(widget_assist["content"], "Where did you visit: ", [0, 2], colour[colour_variable])
location_input = Set_Widgets(widget_assist["input_box"], None, [0, 3], colour["default"], pady=(0, 10), focus=True, width=25)

temp_text = Set_Widgets(widget_assist["content"], "What was your temperature: ", [0, 4], colour[colour_variable])
temp_input = Set_Widgets(widget_assist["input_box"], None, [0, 5], colour["default"], pady=(0, 10))

units_text = Set_Widgets(widget_assist["content"], "Temperature:", [0, 6], colour[colour_variable])
units = Set_Widgets(widget_assist["combobox"], None, [0, 7], colour["default"], values=('celsius', 'fahrenheit'))

submit_button = Set_Widgets(widget_assist["button"], "Add to diary", [0, 8], colour[colour_variable], pady=(20, 20), command=lambda: submit(places))

diary_text = Set_Widgets(widget_assist["content"], "Places I've been to:", [0, 9], colour[colour_variable], pady=(0, 10), size=15)
places = Set_Widgets(widget_assist["content"], DEFAULT_LOCATION, [0, 10], colour[colour_variable], pady=(0, 10))

hottest_place_title = Set_Widgets(widget_assist["content"], "Hottest Place:", [0, 11], colour[colour_variable], pady=(0, 10), size=15)
top_temp_location_text = Set_Widgets(widget_assist["content"], DEFAULT_TOP_TEMPERATURE, [0, 12], colour[colour_variable], pady=(0, 10))


delete_button = Set_Widgets(widget_assist["button"], "Delete all records", [0, 13], colour[colour_variable], pady=(20, 0), command=remove_info)


if temperature > 30:
    colour_variable = "cold"
elif temperature < 30:
    colour_variable = "hot"
else:
    colour_variable = "default"

colour = {"default" : "#FFFFFF", "cold" : "#ABD1F3", "hot" : "#CE2029"}
root.configure(background=colour[colour_variable])

root.mainloop()

流动是字典和钥匙,我想能够自由地使用一个按钮来改变标签的颜色。 有没有更好的办法

colour = {"default" : "#FFFFFF", "cold" : "#ABD1F3", "hot" : "#CE2029"}
colour_variable = "default"

Tags: textselfinputgetvaluelocationwidgetswidget
1条回答
网友
1楼 · 发布于 2024-06-16 14:46:12

在你的温度变量上做一个跟踪,当它改变时触发一个函数

def updateColour(*args):
    #your temp based color selection
    if temperature > 30:
        colour_variable = "cold"
    elif temperature < 30:
        colour_variable = "hot"
    else:
        colour_variable = "default"
    #then change the colors in the stuff you want 
    #below fg is text color, bg background color
    label.config(fg =colour[colour_variable], bg = colour[colour_variable])
    root.configure(background=colour[colour_variable]) 

temperature.trace("w", updateColour)

相关问题 更多 >