介绍一下 threading 和 tkinter

“新人报道”

新人报道

Tkinter是python的标准GUI库,python使用Tkinter可以快速的创建GUI应用程序

https://www.runoob.com/python/python-gui-tkinter.html

from tkinter import messagebox #提示框模块 import tkinter as tk #将tkinter命名为tk top = tk.Tk() #进入消息循环 top.mainloop()

threading

threading是py中用于多线程编程的内置模块,用于创建和管理线程。

import threading # 定义一个函数作为线程的执行体 def worker():    print("Thread started")    # 执行一些耗时操作    for i in range(5):        print(f"Working... {i}")        print("Thread finished") # 创建一个线程对象 thread = threading.Thread(target=worker) # 启动线程 thread.start() # 等待线程结束 thread.join() print("Main thread finished") -------------------------------------------- 输出示例: Thread started Working... 0 Working... 1 Working... 2 Working... 3 Working... 4 Thread finished Main thread finished --------------------------------------------- 基本用法: import threading from selenium.webdriver.common.by import By from selenium import webdriver import time def admin_login(url, username, password):    driver = webdriver.Chrome()    driver.get(url)    driver.find_element(By.XPATH, "//input[@placeholder='请输入用户名']").send_keys(username)    driver.find_element(By.XPATH, "//input[@placeholder='请输入密码']").send_keys(password)    driver.find_element(By.XPATH, "//button[contains(.,'登录')]").click()    time.sleep(1)    # 手动关闭页面才能停止自动化    try:        while True:            time.sleep(1)    except KeyboardInterrupt:        pass    driver.quit() def safe_admin_click():    url = entry.get()    username = "xxxxxx"    password = "xxxxxx"    # 1.创建并启动线程来运行 Selenium 脚本    t = threading.Thread(target=admin_login, args=(url, username, password)) #target后跟函数名,args后跟传参    # 2.启动线程    t.start()    #3.等待线程完成    t.join() ----------------------------------------------------- 4.传递参数给线程函数 def test(name):    print(f"Hello,{name}") # 创建带参数的线程 thread = threading.Thread(target=test,args=("Mason",)) ----------------------------------------------------- 5.设置线程名称 thread = threading.Thread(target=test,name="test") ----------------------------------------------------- 6.使用锁保护共享资源 # 创建锁对象 lock = threading.Lock() def increment():    # counter 为全局变量    global counter    #获取锁    lock.acquire()    try:        counter += 1    finally: #释放锁        lock.release() #创建多个线程并启动 threads = [] for _ in range(10):    t = threading.Thread(target=increment)    t.start    t.append(thread) # 等待所有线程完成 for t in threads:    t.join() # 输出结果可能小于100,因为没有保护共享资源 print(counter)