python-3.x - Tkinter:显示带有自动更新变量的标签
问题描述
我知道关于这个主题有很多问题,但经过长时间的研究,我没有找到任何可以解决我的问题的方法。
我正在尝试使用标签(使用 tkinter)显示从 I²C 总线获得的变量。因此,该变量会非常定期且自动地更新。窗口的其余部分应可供用户使用。
目前,我发现使用更新的变量显示标签并保持窗口的其余部分可供用户使用的唯一方法是这样做:
window = tk.Tk()
window.title("Gestionnaire de périphériques")
window.minsize(1024,600)
labelValThermo = tk.Label(a_frame_in_the_main_window,text = "")
labelValThermo.grid(row = 1, column = 1)
while True:
if mcp.get_hot_junction_temperature() != 16.0625:
labelValThermo.configure(text = "Température thermocouple: {} °C".format(mcp.get_hot_junction_temperature()))
window.update()
time.sleep(0.75)
来自 I²C 并得到更新的变量是mcp.get_hot_junction_temperature
事实是,我知道这不是在无限循环中强制更新的最佳方式。应该是这个角色mainloop()
。我发现该after()
方法可以解决我的问题,但我不知道如何运行它。我尝试了以下不起作用的代码:
def displayThermoTemp():
if mcp.get_hot_junction_temperature() != 16.0625:
labelValThermo.configure(text = "Température thermocouple: {} °C".format(mcp.get_hot_junction_temperature()))
labelValThermo.after(500,displayThermoTemp)
window = tk.Tk()
labelValThermo = tk.Label(thermoGraphFrame,text = "")
labelValThermo.after(500, displayThermoTemp)
labelValThermo.grid(row = 1, column = 1)
window.mainloop()
有没有人有正确的语法?
解决方案
如何使用after()
?
在给定的after()
毫秒延迟后调用函数回调。只需在给定函数中定义它,它就会像 while 循环一样运行,直到你调用after_cancel(id)
.
这是一个例子:
import tkinter as tk
Count = 1
root = tk.Tk()
label = tk.Label(root, text=Count, font = ('', 30))
label.pack()
def update():
global Count
Count += 1
label['text'] = Count
root.after(100, update)
update()
root.mainloop()
用这个更新你的函数并在之前调用它一次mainloop()
。
def displayThermoTemp():
if mcp.get_hot_junction_temperature() != 16.0625:
labelValThermo.configure(text = "Température thermocouple: {} °C".format(mcp.get_hot_junction_temperature()))
labelValThermo.after(500,displayThermoTemp)
# 100ms = 0.1 secs
window(100, displayThermoTemp)
推荐阅读
- python - 标签资源 azure python sdk - 操作合并?
- minecraft - 如何让玩家使用来自 bukkit 插件的副手物品
- dart - Dart 使用 DateTime 对象获取当前工作日
- infix-notation - 如何在 Android 中正确使用中缀表示法(Kotlin 语言)?
- java - 如何使用意图将变量从 MainActivity 传递到 ListAdapter
- ruby-on-rails - 如何通过 SwiftUI urlSession 中的 REST API 将图像数组上传到 Rails 活动存储后端
- html - 我将如何创建一个具有 1 个输入和 6 个不同输出的价格计算器?
- webpack - Webpack 控制台输出
- css - 在滚动负载上居中元素
- javascript - Vue 在每次小的更改时都会不必要地重新渲染整个所有子组件