如何访问类外部的变量(ifrequency和iperiod)?
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
class Parameters:
def __init__(self,master):
tk.Label(master,text='frequency').grid(row=0)
tk.Label(master,text='period').grid(row=1)
self.options1 = ['D1', 'D2']
self.options2 = ['daily', 'monthly']
self.mycombo1 = ttk.Combobox(master, value=self.options1)
self.mycombo1.bind("<<ComboboxSelected>>")
self.mycombo1.grid(row=0, column=1)
self.mycombo2 = ttk.Combobox(master, value=self.options2)
self.mycombo2.bind("<<ComboboxSelected>>")
self.mycombo2.grid(row=1, column=1)
self.myButton = tk.Button(master, text="Go", command=self.clicker).grid(row=3,column=1)
def clicker(self):
ifrequency = self.mycombo1.get()
iperiod = self.mycombo2.get()
return ifrequency, iperiod
p = Parameters(root)
root.mainloop()
print(p.ifrequency)
当运行最后一行时,代码给出错误:"AttributeError:'Parameters‘object没有’ifrequency‘属性“。
为了了解一下上下文,我构建了一些代码来从API中获取输出。我希望用户能够使用表单选择输入(例如频率、周期),然后让主程序调用API并使用这些输入。我的API代码可以工作,但我需要将用户输入分配给一个变量。我可以这样做,但是这个变量卡在函数/类中,我找不到正确的方法来取出它。
这是我在这里的第一个问题(通常是别人在我之前问过的),所以如果我犯了任何错误,请道歉。非常感谢您的帮助!
发布于 2021-02-07 15:11:22
ifrequency
和iperiod
没有赋值给self
,只是在函数的局部作用域中,所以它们在clicker
返回后消失,而且由于它是由tkinter按钮调用的,所以它的返回值不做任何事情。因此,请尝试更改clicker
,以便将它们分配给self
def clicker(self):
self.ifrequency = self.mycombo1.get()
self.iperiod = self.mycombo2.get()
https://stackoverflow.com/questions/66089370
复制