[英]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. 下面是我的代碼的 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()
這可以按我的意願工作,只要我的 cursor 在屏幕上移動,就無需更新 label 文本的 function 。 它在啟動應用程序時工作一次,並且 label 文本保持不變。 每當我的 cursor 移動時,我將如何做到這一點,以便 label 文本更新? 我正在使用 python 3.7
謝謝
將變量賦值給text
參數並沒有幫助,因為即使變量的值發生變化,它也不會反映在 label 中。 這是我的方法(這只是許多可能的方法之一)
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()
筆記
refresh()
,它在無限循環中觸發cursorpixel()
。pixel
為參數的 cursorpixel cursorpixel()
) 中調用了grabColor()
function。color_label.config()
方法更改 label 中的文本,您也可以使用color_label['text']
或者將textvariable
var = StringVar()
分配給 label 然后使用var.set()
它。__name__='__main__'
放在while
循環中是否是一個不錯的選擇,因為您將無法在不終止任務的情況下關閉 window,每次您嘗試這樣做時都會彈出新的。回答\
我將.after
命令添加到grabColor()
function 中,並結合了cursorpixel
和grabColor()
函數。 我使用.config
來更新顏色。 這是代碼:
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()
來源/其他資源
如何使用 Tkinter 創建自動更新的 GUI?
您可以使用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()
請注意,使用winfo_pointerxy()
代替pyautogui.position()
以減少對外部模塊的依賴。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.