python - 如何使用 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。但我无法将这些东西放在一起。
解决方案
我很熟悉,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
推荐阅读
- sharepoint - SharePoint 计时器作业在密码更改后停止工作
- google-apps-script - 将变量内容添加到 HTML 模板中的文本区域
- javascript - 如何在 React js 中获取开始日期和当前月份的日期?
- javascript - 在不刷新页面的情况下更改 URl NEXT.JS
- javascript - 解析充满字符串的对象时 JSON 解析出现 CORS 错误
- segmentation-fault - 链表实现中的分段错误,同时找到它的中间
- zerobrane - 在 zerobrane 的交互式解释器中,math.maxinteger 值为零
- html - bootstrap navbar-toggler 按钮单击将列表项颜色和大小更改为默认值一秒钟?
- python - 我怎样才能把这个 Python 代码变成一个函数?
- python - tkinter 文件目录保存输出