gpt4 book ai didi

Python属性错误: module 'runAnalytics' has no attribute 'run'

转载 作者:行者123 更新时间:2023-12-01 03:45:12 25 4
gpt4 key购买 nike

我正在尝试使用 tkinter 从 main.py 文件中获取输入,然后在 runAnalytics.py 中使用该输入

main.py

import runAnalytics
import tkinter
import os
import centerWindow

loadApplication = tkinter.Tk()
loadApplication.title("Stock Analytics")
loadApplication.geometry("1080x720")

label1 = tkinter.Label(loadApplication, text = "Ticker")
input1 = tkinter.Entry(loadApplication)

loadAnalytics = tkinter.Button(loadApplication, text = "Load Analytics", command = runAnalytics.run)

centerWindow.center(loadApplication)

loadAnalytics.pack()
label1.pack()
input1.pack()

loadApplication.mainloop()

运行分析.py

from yahoo_finance import Share
from main import input1
import tkinter
import os
import centerWindow


def run():
ticker = input1
loadAnalytics = tkinter.Tk()
loadAnalytics.title("$" + ticker + " Data")
loadAnalytics.geometry("1080x720")

print ("Price per share: " + ticker.get_price())

ticker.refresh()
print ("Price per share: " + ticker.get_price())

print("The dividend yield is: " + ticker.get_dividend_yield())

print("The 52 week low is: " + ticker.get_year_low())
print("The 52 week high is: " + ticker.get_year_high())
print("The volume is: " + ticker.get_volume())

print("The previous close was: " + ticker.get_prev_close())
print("The previous open was: " + ticker.get_open())

loadAnalytics.mainloop()

我的错误消息如下;

Traceback (most recent call last):
File "C:\Users\MyName\Documents\Python Projects\MarketData\main.py", line 1, in <module>
import runAnalytics
File "C:\Users\MyName\Documents\Python Projects\MarketData\runAnalytics.py", line 2, in <module>
from main import input1
File "C:\Users\MyName\Documents\Python Projects\MarketData\main.py", line 13, in <module>
loadAnalytics = tkinter.Button(loadApplication, text = "Load Analytics", command = runAnalytics.run)
AttributeError: module 'runAnalytics' has no attribute 'run'

最佳答案

您有一个循环导入:

import runAnalytics
# ..
from main import input1

当再次导入 main 时,runAnalytics 尚未有机会执行 def run():..部分。

通过删除 from main import input1 行来解决此问题,并将该对象作为参数传入:

def run(input1):

调用函数时从 main.py 模块传递此内容:

loadAnalytics = tkinter.Button(loadApplication, text = "Load Analytics", command = lambda: runAnalytics.run(input1))

除了循环导入之外,还存在一个问题,即在 Python 中作为主脚本运行的任何文件都将存储为 __main__ 模块。再次导入相同的脚本将导致创建第二个模块,现在名称为main,并且在该模块中创建的任何对象都与__main__中的对象不同.

接下来,您需要从 run删除 loadAnalytics.mainloop() 调用,因为您不应该从以下位置启动新的主循环一个已经运行的循环。您可能还想创建一个新的 TopLevel 窗口,而不是创建另一个 Tk() 根。如果您这样做,您还必须将 loadApplication 传递给 run

关于Python属性错误: module 'runAnalytics' has no attribute 'run' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39045091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com