8 - 多线程

|- 8.1-开启线程

注:线程函数默认不循环执行

语法:线程对象 = GUI对象.start_thread(线程函数名)

  • 返回值: 线程对象
  • 输入参数: 线程函数名
  • 用法举例:
import time
from unihiker import GUI   #导入包
gui=GUI()  #实例化GUI类

clock = gui.draw_clock(x=120, y=160, r=100, h=3, m=4, s=5, color=(255, 0, 0), onclick=lambda: print("clock clicked"))
def clock_update():
    print("线程1启动")
    while True: #循环执行
        t = time.localtime()
        clock.config(h=time.strftime("%H", t), m=time.strftime("%M", t), s=time.strftime("%S", t))
        time.sleep(0.5) #在线程循环中加入sleep可以防止程序卡住或变慢
    print("线程1停止")

def print_test():
    print("线程2启动")
    time.sleep(1)
    print("线程2")
    time.sleep(1)
    print("线程2结束")

#线程1启动
clock_thread = gui.start_thread(clock_update)
#线程2启动
gui.start_thread(print_test)

while True:
    time.sleep(0.1)

|- 8.2-停止线程

语法:GUI对象.stop_thread(线程对象)

  • 返回值:
  • 输入参数: 线程对象
  • 用法举例:
import time
from unihiker import GUI   #导入包
gui=GUI()  #实例化GUI类

clock = gui.draw_clock(x=120, y=160, r=100, h=3, m=4, s=5, color=(255, 0, 0), onclick=lambda: print("clock clicked"))
def clock_update():
    while True:
        t = time.localtime()
        clock.config(h=time.strftime("%H", t), m=time.strftime("%M", t), s=time.strftime("%S", t))
        time.sleep(0.5)
	    #gui.stop_thread(clock_loop)#线程内可以停止

#多线程启动
clock_thread = gui.start_thread(clock_update)
time.sleep(6)
#停止线程
gui.stop_thread(clock_thread)

while True:
    time.sleep(0.1)

----------------

9 - 其他GUI类功能

|- 9.1-更新GUI gui.update()

注意,此函数仅在MAC系统下运行unihiker库时需要,用于在主线程中刷新界面,控制行空板时无需此函数。

**语法:**GUI对象.update()

  • 返回值:
  • 输入参数:
  • 用法举例:
import time
from unihiker import GUI   #导入包
gui=GUI()  #实例化GUI类

clock = gui.draw_clock(x=120, y=160, r=100, h=3, m=4, s=5, color=(255, 0, 0), onclick=lambda: print("clock clicked"))

while True:
    gui.update()
    time.sleep(0.1)