我正在尝试从main.py获取用户输入,然后将输出定制到所述用户输入。我不仅得到了这个错误,而且当我启动main.py时,似乎我的runAnalytics正在运行,而不是当我点击我的按钮命令时这样做。
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(input1))
centerWindow.center(loadApplication)
loadAnalytics.pack()
label1.pack()
input1.pack()
loadApplication.mainloop()
runAnalytics.py
from yahoo_finance import Share
import tkinter
import os
import centerWindow
def run(input1):
ticker = Share(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()
错误讯息:
追踪(最近一次通话): 文件" C:\ Users \ MyName \ Documents \ Python Projects \ MarketData \ main.py",第13行,in loadAnalytics = tkinter.Button(loadApplication,text =" Load Analytics",command = runAnalytics.run(input1)) 文件" C:\ Users \ MyName \ Documents \ Python Projects \ MarketData \ runAnalytics.py",第12行,在运行中 打印("每股价格:" + ticker.get_price()) AttributeError:' str'对象没有属性' get_price'
答案 0 :(得分:1)
您对runAnalytics
正在运行的假设是正确的,因为在按照您的方式将其绑定到按钮时执行该函数。
根据effbot docs你需要使用lambda
函数来将函数与传递的参数绑定到这样的按钮:
import tkinter
def test_func(val):
print(type(val))
print(val)
share_id = val.get()
print(share_id)
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=lambda: test_func(input1))
loadAnalytics.pack()
label1.pack()
input1.pack()
loadApplication.mainloop()
然而,还有第二件事要记住:
input1 = tkinter.Entry(loadApplication)
创建一个名为Entry
的{{1}}窗口小部件,然后传递给该函数。问题是input1
不包含您在条目小部件中键入的字符串,而是包含对小部件的引用(小部件ID)。要获取小部件的内容,您需要调用其input1
方法,如我的代码段所示。