52ky 发表于 2022-5-6 15:54:03

线程和 Tkinter/Python3

问题
我需要帮助连接 Tkinter 的附加流。我需要不断更新Label中的光标坐标,但我就是想不通(+如果可能的话,你能告诉我如何构造一个像这样的变量:“text”,这里是Label(text= “坐标:”,字体=“Arial 12”)。
import win32api
from threading import Thread
from tkinter import *
root = Tk()
#Подключение модулей}

#Переменные{
xcoord = "null"
ycoord = "null"
h_x = 0
h_y = 0
#Переменные}
root.title("Utility")
root.geometry("400x500+100+100")
root.columnconfigure(0, weight=1)
root.resizable(False, False)
#root.iconbitmap('') Иконка
root["bg"] = "grey30"
def coordinates():
    while True:
      h_x, h_y = win32api.GetCursorPos()
      print(h_x, h_y)

#Лейбл показа координат{
select_mode = Label(text="Координаты:", font="Arial 12")
select_mode['bg'] = "grey30"
select_mode['fg'] = "white"
select_mode.place(x="10", y="470")

select_mode = Label(text='x = ', font="Arial 12")
select_mode['bg'] = "grey30"
select_mode['fg'] = "white"
select_mode.place(x="120", y="470")

select_mode = Label(text=h_x, font="Arial 12")
select_mode['bg'] = "grey30"
select_mode['fg'] = "white"
select_mode.place(x="140", y="470")

select_mode = Label(text='y = ', font="Arial 12")
select_mode['bg'] = "grey30"
select_mode['fg'] = "white"
select_mode.place(x="200", y="470")

select_mode = Label(text=h_y, font="Arial 12")
select_mode['bg'] = "grey30"
select_mode['fg'] = "white"
select_mode.place(x="220", y="470")


coord_thread = Thread(target = coordinates)
coord_thread.run()
coord_thread.join()

root.mainloop()

回答
您可能不需要线程来执行此操作。

您可以使用 root.after() 重新执行坐标:
# other stuff as before, except the creation of these labels:
select_mode_x = Label(text=h_x, font="Arial 12")
select_mode_x['bg'] = "grey30"
select_mode_x['fg'] = "white"
select_mode_x.place(x="140", y="470")

select_mode_y = Label(text=h_y, font="Arial 12")
select_mode_y['bg'] = "grey30"
select_mode_y['fg'] = "white"
select_mode_y.place(x="220", y="470")

# Moved coordinates function down here
def coordinates():
    h_x, h_y = win32api.GetCursorPos()
    print(h_x, h_y)
    select_mode_x.config(text=h_x)
    select_mode_y.config(text=h_y)
    root.after(100, coordinates)

coordinates()
root.mainloop()



页: [1]
查看完整版本: 线程和 Tkinter/Python3