[英]how to get tkinter input outside of function within class
How do I get access to variables (ifrequency and iperiod) outside of the class?如何访问 class 之外的变量(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)
The code gives the error: "AttributeError: 'Parameters' object has no attribute 'ifrequency'" when running the final line.代码在运行最后一行时出现错误:“AttributeError: 'Parameters' object has no attribute 'ifrequency'”。
For a bit of context, I have built some code to get output from an API.对于一些上下文,我构建了一些代码来从 API 获取 output。 I want the user to be able to pick the inputs (eg frequency, period) using a form and then have the main program call the API and using these inputs.
我希望用户能够使用表单选择输入(例如频率、周期),然后让主程序调用 API 并使用这些输入。 My API code works but I need to get the user inputs assigned to a variable.
我的 API 代码有效,但我需要将用户输入分配给变量。 I can do it but that variable is stuck in the function/class and I can't figure out the correct way to get it out.
我可以做到,但该变量卡在函数/类中,我无法找出正确的方法将其取出。
This is my first question here (usually someone else has asked before me) so apologies if I have made any mistakes.这是我在这里的第一个问题(通常是其他人在我之前问过的),所以如果我犯了任何错误,我深表歉意。 Many thanks in advance for your help!
非常感谢您的帮助!
ifrequency
and iperiod
are not assigned to self
and are just in the function's local scope so they disappear after clicker
returns, and since it is called by the tkinter button, it's return value dosn't do anything. ifrequency
和iperiod
没有分配给self
并且只是在函数的本地 scope 所以它们在clicker
返回后消失,并且由于它被 tkinter 按钮调用,它的返回值没有做任何事情。 so try changing clicker
so it assigns them to self
所以尝试更改
clicker
,以便将它们分配给self
def clicker(self):
self.ifrequency = self.mycombo1.get()
self.iperiod = self.mycombo2.get()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.