[英]Is there any way how to print "changing" variable in Python tkinter canvas?
I've got some variable in while loop:我在while循环中有一些变量:
import pyautogui as py
while True:
x, y = py.position()
Is there any way how to print these variables in tkinter window - in for example label, even when it is while loop?有什么方法可以在 tkinter window 中打印这些变量 - 例如 label,即使它是 while 循环? Or is there any way how to print "changing" variable in tkinter label?或者有什么方法可以在 tkinter label 中打印“更改”变量?
In tkinter
you should rather use root.after(milliseconds, function_name)
instead of while
-loop because while
-loop will block mainloop
and tkinter
will freeze.在tkinter
,您应该使用root.after(milliseconds, function_name)
而不是while
-loop,因为while
-loop 会阻塞mainloop
而tkinter
会冻结。 Using after
it will send information to mainloop
and it will run it after milliseconds
and it will have also time to get mouse/key events from system, send them to widgets and update/redraw all widgets in window so it will not freeze.使用after
它将信息发送到mainloop
并在milliseconds
后运行它,它还有时间从系统获取鼠标/键事件,将它们发送到小部件并更新/重绘 window 中的所有小部件,因此它不会冻结。
import tkinter as tk
import pyautogui as py
# --- functions ---
def update_label():
x, y = py.position()
label['text'] = f'{x}, {y}'
root.after(25, update_label) # run again after 25ms
# --- main ---
root = tk.Tk()
label = tk.Label(root) # with empty text
label.pack(padx=5, pady=5)
#update_label() # run first time at once
root.after(25, update_label) # run first time after 25ms
root.mainloop()
If you really have to use while
-loop then you will have to use root.update()
to force mainloop
to update widgets in window.如果你真的必须使用while
-loop,那么你将不得不使用root.update()
来强制mainloop
更新 window 中的小部件。
import tkinter as tk
import pyautogui as py
# --- main ---
root = tk.Tk()
label = tk.Label(root) # with empty text
label.pack(padx=5, pady=5)
while True:
x, y = py.position()
label['text'] = f'{x}, {y}'
root.update()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.