Python 从Tkinter输入框中检索值
我试图让Tkinter从输入框返回值,但似乎无法让它工作 这是我第一次尝试把Tkinter拿出来,sPython 从Tkinter输入框中检索值,python,tkinter,Python,Tkinter,我试图让Tkinter从输入框返回值,但似乎无法让它工作 这是我第一次尝试把Tkinter拿出来,s Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\rik\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__ return s
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\rik\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "n:\regnskab\Afregning\RIK\Udvikling\gui\app2.py", line 43, in step_1
periode_2 = get_period(self)
NameError: name 'get_period' is not defined
您必须学习OOP:)
get\u period()
不是独立函数,但它是类UserInputFrame
中的函数,您尝试在类ControlsFrame
中访问它。您不能以这种方式访问另一个类中某个类的函数
您必须获取UserInputFrame
的实例
user_input_frame = UserInputFrame(self)
user_input_frame.grid(row=1, column=0)
将其作为参数发送到ControlsFrame
ControlsFrame(self, user_input_frame).grid(row=2, column=0)
self.user_input_frame = UserInputFrame(self)
self.user_input_frame.grid(row=1, column=0)
periode_2 = self.master.user_input_frame.get_period() # without `self` in `get_period()`
将其保存在类变量中
class ControlsFrame(ttk.Frame):
def __init__(self, container, user_input_frame):
super().__init__(container)
self.user_input_frame = user_input_frame
然后你就可以使用它了
def step_1(self):
self.user_input_frame.get_period() # without `self` in `get_period()`
还是更好的方法 您应该将
UserInputFrame
分配到Mainframe
ControlsFrame(self, user_input_frame).grid(row=2, column=0)
self.user_input_frame = UserInputFrame(self)
self.user_input_frame.grid(row=1, column=0)
periode_2 = self.master.user_input_frame.get_period() # without `self` in `get_period()`
然后其他对象(在大型机
中创建)可以使用self.master
访问大型机
(即其paret/master),然后它们可以访问大型机
中的元素,如self.master.userinputframe
ControlsFrame(self, user_input_frame).grid(row=2, column=0)
self.user_input_frame = UserInputFrame(self)
self.user_input_frame.grid(row=1, column=0)
periode_2 = self.master.user_input_frame.get_period() # without `self` in `get_period()`
顺便说一句:在
按钮框架
中,您忘记了自我。
在命令=self中。退出并在应用程序.destroy()中退出(
)
EDIT:as@acw1668注意到函数get_period()
不从条目返回值-它只打印它-因此它需要return
def get_period(self):
return self.entry_year.get()
你必须学习OOP
get\u period
不是独立的函数,而是类UserInputFrame
中的函数-因此您必须获取UserInputFrame
的实例,将其作为参数发送到ControlsFrame
,然后使用control\u框架的实例。get\u period()
您不能在一个类中从另一个类访问函数。请注意get\u period()
returnNone
。将其更改为def get_period(self):返回self.entry\u year.get()
@acw1668 good point:)我将其添加到了answer中谢谢-使用第二种方法可以使用它。为什么你认为这个优于第一个?第二个版本是通用的——所有的类都可以访问<代码> UsRyInPosikFrase。同样,您可以在按钮框架
中访问self.master.user\u input\u frame
。如果您在主窗口中添加了另一个小部件,那么它也可以访问self.master.user\u input\u frame
。类似地,您可以设置self.control\u frame=ControlsFrame(…)
,其他小部件将可以使用self.master.control\u frame
访问control\u frame
。