如何刷新 python 中的文本?

How do I refresh text in python?

我在 Gnu/Linux 上有一个 python 应用程序。该程序从内核启用或禁用摄像头和麦克风。除了一个我无法解决的小问题外,该程序运行良好。该程序有 4 个按钮。有 2 个按钮可以启用摄像头和麦克风,还有两个按钮可以禁用它们。有四个文本:Camera is not loadedCamera is loadedMicrophone is loadedMicrophone is not loaded

问题:

问题是消息显示了两个文本。它显示 Camera is loadedCamera not loaded。例如,当我第一次打开应用程序时,它显示相机未加载。当我按下按钮启用相机时,文本显示相机已加载,但问题是未加载的文本相机不会被删除。它同时显示消息 Camera is loadedCamera not loaded。如果我退出程序并再次加载问题已解决,它只显示消息 camera is loaded。我想在不退出程序重新加载的情况下刷新新消息

谁能帮我解决这个问题?

这是Python程序:

def update():
    root.after(1000, update)  # run itself again after 1000 ms
    var1()

def var1():
    var1 = StringVar()
    exit_code_cam = os.system("lsmod |grep uvcvideo")
    load = "Camera is loaded"
    notLoad = "Camera not loaded"

    if exit_code_cam == 0:
        l1 = Label(root, textvariable=var1, fg="green")
        l1.place(x=2, y=30)
        var1.set(load)
    else:
        l1 = Label(root, textvariable=var1, fg="red")
        l1.place(x=2, y=10)
        var1.set(notLoad)

def button_add1():
    cam_mic_bash.enable_cam()
    var1()

def button_add3():
    cam_mic_bash.disable_cam()
    var1()

# Define Buttons
button_1 = Button(root, text="Allow camera", width=20, height=5, padx=0, pady=0, command=button_add1)
button_3 = Button(root, text="Block camera", width=20, height=5, padx=0, pady=0, command=button_add3)

# Put the buttons on the screen
button_1.place(x=0, y=75)
button_3.place(x=0, y=150)

# run first time
update()

root.mainloop()

与其一遍又一遍地创建新标签,不如创建一次标签并根据您的要求进行配置,á la

import os
from tkinter import StringVar, Tk, Label, Button

root = Tk()
camera_loaded_stringvar = StringVar()
camera_label = Label(root, textvariable=camera_loaded_stringvar)
camera_label.place(x=2, y=10)

def update_loop():
    root.after(1000, update_loop)  # run itself again after 1000 ms
    update_camera_label()


def update_camera_label():
    is_loaded = os.system("lsmod | grep uvcvideo") == 0
    if is_loaded:
        camera_loaded_stringvar.set("Camera is loaded")
        camera_label.configure(fg="green")
    else:
        camera_loaded_stringvar.set("Camera not loaded")
        camera_label.configure(fg="red")


def button_add1():
    enable_cam()
    update_camera_label()


def button_add3():
    disable_cam()
    update_camera_label()


allow_camera_button = Button(root, text="Allow camera", width=20, height=5, padx=0, pady=0, command=button_add1)
block_camera_button = Button(root, text="Block camera", width=20, height=5, padx=0, pady=0, command=button_add3)

allow_camera_button.place(x=0, y=75)
block_camera_button.place(x=0, y=150)

update_loop()
root.mainloop()