You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在stop_show函数外访问spw、wps变量并导入至其他模块函数?

解决Tkinter函数内变量外部访问及跨模块导入问题

针对你需要在stop_show()外部访问wps和spw,并能导入到其他模块的需求,这里提供三种可行方案:

方案一:使用全局变量

直接将wps和spw声明为全局变量,函数执行后外部代码和其他模块就能访问到它们。

修改后的关键代码:

# 全局作用域提前声明变量(避免未定义报错)
wps = 0.0
spw = 0.0

def stop_show():
    global end_time, elapsed_time, wps, spw
    end_time = time.time()
    elapsed_time = end_time - start_time
    print(f"Time elapsed: {round(elapsed_time, 2)}")
    wps = words/elapsed_time
    spw = elapsed_time/words
    print(f"Your current WPS (Words per second): {round(wps, 2)}")  
    print(f"Your current SPW (Seconds per word): {round(spw, 2)}")  

其他模块导入时,直接调用:

import your_module_name

# 确保stop_show执行后再访问
print(your_module_name.wps)
print(your_module_name.spw)

注意:必须先触发stop_show(),否则变量会保持初始值0.0。

方案二:让函数返回计算结果

把stop_show()改成返回wps和spw,通过按钮的回调函数捕获结果并存储,方便外部访问。

修改后的代码:

def stop_show():
    global end_time, elapsed_time
    end_time = time.time()
    elapsed_time = end_time - start_time
    print(f"Time elapsed: {round(elapsed_time, 2)}")
    wps = words/elapsed_time
    spw = elapsed_time/words
    print(f"Your current WPS (Words per second): {round(wps, 2)}")  
    print(f"Your current SPW (Seconds per word): {round(spw, 2)}")
    return wps, spw  # 返回计算结果

# 全局变量存储结果
result_wps = 0.0
result_spw = 0.0

def on_stop():
    global result_wps, result_spw
    result_wps, result_spw = stop_show()

# 修改按钮的command为自定义回调
Stop_btn = Button(root, text="Stop", fg="red",
                  width=25, height=5, command=on_stop)

其他模块需要访问时,导入全局的result_wps和result_spw即可。

方案三:用类封装(推荐)

把整个应用逻辑封装到类中,wps和spw作为实例属性,避免全局变量混乱,更适合跨模块调用。

完整修改后的代码:

from tkinter import *
import time

class ReadzyApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Readzy")
        
        self.para = "India is one of the youngest superpowers in the world.\n The National bird of India is the peacock, which has\n a very colourful and beautiful tail. The national flower of\n India is Lotus. Lotus comes in many colours, white and pink \nbeing prominent.The National animal of India is the Royal\n Bengal tiger."
        self.words = len(self.para.split())
        
        self.start_time = None
        self.wps = 0.0
        self.spw = 0.0
        
        self._setup_ui()
    
    def _setup_ui(self):
        self.para_label = Label(self.root, text=self.para, bg="red",
                               font="comicsansms 23 bold", width=100, height=10)
        self.para_label.pack(fill=X)
        
        self.Start_btn = Button(self.root, text="Start", command=self.start,
                               fg="red", width=25, height=5)
        self.Stop_btn = Button(self.root, text="Stop", fg="red",
                              width=25, height=5, command=self.stop_show)
        
        self.Start_btn.pack(anchor=S, side=TOP)
        self.Stop_btn.pack(side=TOP, anchor=S)
    
    def start(self):
        self.start_time = time.time()
    
    def stop_show(self):
        if not self.start_time:
            print("请先点击Start按钮开始计时")
            return
        elapsed_time = time.time() - self.start_time
        print(f"Time elapsed: {round(elapsed_time, 2)}")
        self.wps = self.words / elapsed_time
        self.spw = elapsed_time / self.words
        print(f"Your current WPS (Words per second): {round(self.wps, 2)}")  
        print(f"Your current SPW (Seconds per word): {round(self.spw, 2)}")

if __name__ == "__main__":
    root = Tk()
    app = ReadzyApp(root)
    root.mainloop()

其他模块导入时,通过实例访问属性:

from your_module_name import ReadzyApp
import tkinter as tk

root = tk.Tk()
app = ReadzyApp(root)
# 触发stop_show后即可访问
print(app.wps)
print(app.spw)

这种方式结构清晰,变量封装在实例内,不会污染全局命名空间,是大型项目的推荐做法。

内容的提问来源于stack exchange,提问作者Devesh Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:05:36