[英]How to inherit a variable from module under tkinter in Python3.6
I'm beginner with Python. 我是Python的新手。 Q: I have two modules and I would to use a variable (self.vari) that exists in the module2, but I still have the same error ( AttributeError: type object 'mod2Class' has no attribute 'vari' ) even trying another way.
问:我有两个模块,我将使用存在于module2中的变量(self.vari),但是我仍然遇到相同的错误( AttributeError:类型对象'mod2Class'没有属性'vari' ),甚至尝试了另一种方法。
I'll samplify that with the following code: 我将使用以下代码对其进行简化:
========= #Module2: ========= #Module2:
import tkinter as tk
class mod2Class:
def __init__(self, parent):
self.vari=tk.StringVar()
self.vari.set('Variable Value')
self.txtBox2 = tk.Text(parent, width=10)
self.txtBox2.grid(row=0, column=2)
#Module1 #模块1
import tkinter as tk
from mod2 import mod2Class
class mod1Class(mod2Class):
def __init__(self,parent):
mod2Class.__init__(self,parent)
self.lbl1=tk.Label(parent,width=15,text=mod2Class.vari)
self.lbl1.grid(row=0,column=0)
s=tk.Tk()
n=mod1Class(s)
s.mainloop()
===================== =====================
I would appreciate any help 我将不胜感激任何帮助
In module 1 you've referred to the variable you want as: 在模块1中,您将所需的变量称为:
mod2Class.self.vari
You've called mod2Class. 您已将其称为mod2Class。 init () with self as the first parameter, which makes your class in module 1 an instance of mod2Class.
init (),第一个参数为self,这使模块1中的类成为mod2Class的实例。 You also want to get the text from the variable, not just the object.
您还想从变量中获取文本,而不仅仅是对象。 Therefore, change that line to:
因此,将该行更改为:
self.vari.get()
After a bit of research, I've confirmed my other thought, which is that you need to pass a Tk window to your StringVar. 经过一些研究,我证实了我的另一种想法,那就是您需要将Tk窗口传递给StringVar。 Try passing your parent window when you create self.vari.
创建self.vari时,请尝试传递父窗口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.