简体   繁体   English

如何实时更新 tkinter label 文本

[英]How to update tkinter label text in real time

I have an application that gets the css3 colour of the pixel your cursor is on, and I would like to use tkinter to display the text in a little window. I have an application that gets the css3 colour of the pixel your cursor is on, and I would like to use tkinter to display the text in a little window. I following is the tkinter part of my code:下面是我的代码的 tkinter 部分:

import pyautogui, PIL
import tkinter as tk

def cursorpixel():
    x,y = pyautogui.position()
    pixel = (x,y,x+1,y+1)
    return pixel

def grabColor(square, max_colors=256):
    img=PIL.ImageGrab.grab(square)
    color = img.getcolors(max_colors)
    return color

def main():
    root=tk.Tk()
    root.minsize(150, 50)
    color = tk.Label(root,
                     text= grabColor(cursorpixel()),
                     fg = "black",
                     font = "Arial").pack()
    root.mainloop()

while __name__ == "__main__":
    main()

This works as I want, without the function of updating the label text whenever my cursor moves across the screen.这可以按我的意愿工作,只要我的 cursor 在屏幕上移动,就无需更新 label 文本的 function 。 It works once when launching the application and the label text stays the same.它在启动应用程序时工作一次,并且 label 文本保持不变。 How would I make it so the label text updates whenever my cursor moves?每当我的 cursor 移动时,我将如何做到这一点,以便 label 文本更新? I am using python 3.7我正在使用 python 3.7

Thank you谢谢

Assigning a variable to the text argument doesn't help, because even if the value of the variable changes, it will not be reflected in the label.将变量赋值给text参数并没有帮助,因为即使变量的值发生变化,它也不会反映在 label 中。 Here is my approach to this (this is just one out of many possible ways)这是我的方法(这只是许多可能的方法之一)

import pyautogui, PIL
import tkinter as tk
from threading import Thread

def cursorpixel():
    x,y = pyautogui.position()
    pixel = (x,y,x+1,y+1)
    grabColor(pixel)

def grabColor(square, max_colors=256):
    global color_label,root
    img=PIL.ImageGrab.grab(square)
    color = img.getcolors(max_colors)
    color_label.config(text=color)

def refresh():
    while True:
        cursorpixel()

def main():
    global color_label,root
    root=tk.Tk()
    root.minsize(150, 50)
    color_label = tk.Label(root,
                     fg = "black",
                     font = "Arial")
    color_label.pack()
    Thread(target=refresh).start()
    root.mainloop()

if __name__ == "__main__":
    main()

NOTES笔记

  • I have used multi threading instead and created a function refresh() which triggers the cursorpixel() in an infinite loop.我改用了多线程并创建了一个 function refresh() ,它在无限循环中触发cursorpixel()
  • I have called the grabColor() function from cursorpixel() having pixel as parameter.我从以pixel为参数的 cursorpixel cursorpixel() ) 中调用了grabColor() function。
  • I have used the color_label.config() method to change the text in the label, you could also use color_label['text'] or maybe assign a textvariable var = StringVar() to the label and then use var.set() on it.我已使用color_label.config()方法更改 label 中的文本,您也可以使用color_label['text']或者将textvariable var = StringVar()分配给 label 然后使用var.set()它。
  • I am not sure if it is a good choice to put the __name__='__main__' in a while loop as you will not be able to close the window without terminating the task, new one will pop up every time you try to do so.我不确定将__name__='__main__'放在while循环中是否是一个不错的选择,因为您将无法在不终止任务的情况下关闭 window,每次您尝试这样做时都会弹出新的。

Answer \回答\

I added the .after command into the grabColor() function and combined the cursorpixel and grabColor() functions.我将.after命令添加到grabColor() function 中,并结合了cursorpixelgrabColor()函数。 I used .config to update the color.我使用.config来更新颜色。 Here is the code:这是代码:

import pyautogui, PIL
from tkinter import *

root=Tk()
root.minsize(150, 50)
colortext = Label(root)
colortext.pack()

def grabColor():
    x,y = pyautogui.position()
    pixel = (x,y,x+1,y+1)
    img=PIL.ImageGrab.grab(bbox=pixel)
    color = img.getcolors()
    colortext.config(text=str(color))
    root.after(100, grabColor)

grabColor()

root.mainloop()

Sources / Additional Resources来源/其他资源
How do I create an automatically updating GUI using Tkinter? 如何使用 Tkinter 创建自动更新的 GUI?

You can use after() to grab the color periodically:您可以使用after()定期获取颜色:

import tkinter as tk
from PIL import ImageGrab

def grab_color(label):
    x, y = label.winfo_pointerxy()
    color = ImageGrab.grab((x, y, x+1, y+1)).getpixel((0, 0))
    label.config(text=str(color))
    label.after(100, grab_color, label)

def main():
    root = tk.Tk()
    color_label = tk.Label(root, width=20)
    color_label.pack(padx=10, pady=10)
    grab_color(color_label)
    root.mainloop()

if __name__ == "__main__":
    main()

Note that winfo_pointerxy() is used instead of pyautogui.position() to reduce dependency on external module.请注意,使用winfo_pointerxy()代替pyautogui.position()以减少对外部模块的依赖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM