首页 > 解决方案 > 如何使用 python GUI 创建指示灯(危险、警告、安全)

问题描述

基本上我正在尝试构建一个 GUI,其中将根据条件生成一些警告灯。例如我有:

arr = [5,6,7,8,3,2,4,1]

for each in arr:
   if each < 3:
      show red circle in gui as "danger"
   if each > 3 and each < 7:
      show yellow circle in gui as "warning"
   if each > 7:
      show green circle in gui as "safe"

我已经尝试过 tkinter 但我无法让它工作,似乎遗漏了一些逻辑。注意:我知道如何使用 tkinter 创建 GUI。但我无法将这些东西放在一起。

标签: pythontkinter

解决方案


我很熟悉,Tkinter我已经为你写了一个例子。为了更好地理解,我在代码中写了几条注释。

代码:

import tkinter as tk
import time

arr = [5, 6, 7, 8, 3, 2, 4, 9]  # Set the list of numbers


def start_indicators():
    """
    This function updates the widgets based on your list
    :return: None
    """

    for x in arr:  # Iterate through the list.
        label_text = "Current value: {}".format(x)  # Set the text of Label
        if x < 3:
            print("Value: {} - Danger!".format(x))
            my_canvas.itemconfig(my_oval, fill="red")  # Fill the circle with RED
            label_var.set(label_text)  # Updating the label
        elif 3 < x < 7:
            print("Value: {} - Warning!".format(x))
            my_canvas.itemconfig(my_oval, fill="yellow")  # Fill the circle with YELLOW
            label_var.set(label_text)  # Updating the label
        elif x > 7:
            print("Value: {} - Safe!".format(x))
            my_canvas.itemconfig(my_oval, fill="green")  # Fill the circle with GREED
            label_var.set(label_text)  # Updating the label
        root.update()  # Update the complete GUI.
        time.sleep(2)  # Sleep two secs
    print("FINISH")


root = tk.Tk()  # Set Tk instance

my_canvas = tk.Canvas(root, width=200, height=200)  # Create 200x200 Canvas widget
my_canvas.pack()

my_oval = my_canvas.create_oval(50, 50, 100, 100)  # Create a circle on the Canvas

label_var = tk.StringVar()  # Set the string variable for Label widget

my_label = tk.Label(root, textvariable=label_var)  # Set the LAbel widget
my_label.pack()

my_button = tk.Button(root, text="START", command=start_indicators)  # Set a "Start button". The "start_indicators" function is a call-back.
my_button.pack()

root.mainloop()

图形用户界面:

绿色的 黄色 红色的

控制台输出:

>>> python3 test.py 
Value: 5 - Warning!
Value: 6 - Warning!
Value: 8 - Safe!
Value: 2 - Danger!
Value: 4 - Warning!
Value: 1 - Danger!
FINISH

推荐阅读