I'm trying to break a tkinter app with several classes into multiple .py files. I'm using a Mixin class to import methods into each class. However, I'm struggling to access variables.
main.py contains a class creating the main window with a button to open a top level window and a button to get a variable from the Mixin.
# main.py
import tkinter
from tkinter import Tk
import customtkinter
import sys
sys.path.insert(1, "path/Classes")
from Classes import topLevel
# Main Window
class App(customtkinter.CTk):
def __init__(self):
super().__init__()
# Top Level Button
self.topLevel_button = customtkinter.CTkButton(master=self,
text="Open",
command=self.openTopLevel)
self.topLevel_button.grid(row=0, column=0)
# Get Variable
self.get_button = customtkinter.CTkButton(master=self,
text="Get Variable",
command=self.getVariable)
self.get_button.grid(row=1, column=0)
def openTopLevel(self):
window = topLevel.topLevel(self)
def getVariable(self):
print(var) # Can't access var
if __name__ == "__main__":
app = App()
app.mainloop()
topLevel.py is a class creating the top level window. It contains a variable fileSep to be used by a method in the Mixin Class:
# topLevel.py
sys.path.insert(1, "path/Methods")
from Methods import _topLevel
class topLevel(customtkinter.CTkToplevel, _topLevel.Mixin):
def __init__(self, parent):
super().__init__(parent)
# Create Variable
global fileSep
fileSep = customtkinter.StringVar(value="Comma")
print("Inside Class: " + fileSep.get()) # Works
# Create Button
self.loadButton = customtkinter.CTkButton(master=self,
text="Load",
command=self.loadFile)
self.loadButton.grid(row=0, column = 0, sticky='nswe')
# Attempt to access variable
def access_method(self):
print("Access Method: " + self.fileSep.get())
And _topLevel.py contains the mixin class:
# _topLevel.py
class Mixin:
def loadFile(self):
# Trying to access fileSep variable
print("Inside Mixin: " + fileSep.get()) # Error
topLevel().access_method() # Error
# I'm trying to access this variable from a function in main.py
var = "Hello World"
I get the following errors because the variables aren't accessible.
NameError: name 'var' is not defined
NameError: name 'fileSep' is not defined
I've tried making variables global as well as creating methods inside the class ( access_method() ) to print the variables as described here https://www.geeksforgeeks.org/python-using-variable-outside-and-inside-the-class-and-method/, but get the error:
TypeError: __init__() missing 1 required positional argument: 'parent'
How do I access variables that are defined in a class in the Mixin class? How would I access a variable created by the loadFile function in the Mixin Class for use in methods in the class App?
Thanks to #acw1668 comment, I just needed to make fileSep an instance variable:
self.fileSep = customtkinter.StringVar(value="Comma")
And to access it in the mixin class:
print("Inside Mixin: " + self.fileSep.get())
Equally I could create an instance variable to assign variable var to. For example in the topLevel class I added:
self.a = ""
And then assigned var to this variable within the function:
var = "Hello World"
self.a = var
Related
In MyFactory.scala, object and Class defined in the same file with same name, like this
package com.mydomain.app.module
object MyFactory{
val a1 = "a1"
val b1 = "b1"
}
class MyFactory(config:Configuration){
//blah....
}
Problem is I cannot Initiate MyFactory object in another class
var myFactory = new Myfactory(defaultConfiguration)
due to the error
not found: type MyFactory
All I did was a common import
import com.mydomain.app.module.MyFactory
What is the valid way to initiate an object of the class, if I can't modify anything from MyFactory.scala (legacy code)
var myFactory = new MyFactory(defaultConfiguration)
is the valid way to initiate an object of the class.
import com.mydomain.app.module.MyFactory should be enough for bringing MyFactory (and its companion) to the scope.
Sometimes "object app is not a member of package com.mydomain" can mean that you're trying to recompile MyFactory.scala referring to something not compiled in com.mydomain...
Try mvn clean compile.
I have a Jenkins file, and i'm trying to instantiate a groovy class from my shared library. I get "unable to resolve class Test "
I have a src/com/org/foo.groovy file in a shared library :
package com.org
class Test implements Serializable{
String val
Test(val) {
this.val = val
}
}
and I'm trying to instantiate it in my jenkinsfile
#Library('Shared-Library#master')
import com.org //also tried to use with .foo with no success
def t = new Test("a") //doesnt work
def t = new foo.Test("a")//doesnt work
def t = new com.org.foo.Test("a")//doesnt work
What does work is if I refer to the file as a class (which I don't have the access to its constructor). That is:
#Library('Shared-Library#master')
def t = new foo.com.org.foo()
This is nice, and lets me use foo functions. However, I lose the power to give the class constants and construct it with parameters.
Any idea how I can define and use a class from shared library?
Thanks
The scope of your class is a default scope. you can change the scope to public
It throwing an error because you have created an object of a class outside the script block. try below code and it should work. Try below code
#Library('Shared-Library#master')
import com.org.*;
stages{
stage('Demo') {
steps{
script{
def t = new Test("a") //this should work
}
}
}
}
I wondered if anyone could tell me is it possible to divide the following code into two python classes which will then be placed in two different files:
from GUI import mainGUI
from GUI import subwindowGUI
class MyApp(QMainWindow, mainGUI.Ui_MainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setupUi(self)
# mainGUI contains QMdiarea in which it opens
# a subwindow by calling a function MySubWin(self)
# QMdiarea name is 'body'
self.OpenSub.triggered.connect(self.MySubWin)
def MySubWin(self):
self.MySubWin = QWidget()
self.MySubWin.setObjectName('Module window')
self.myTabs = QtabWidget(self.MySubWin)
self.myTabs.setObjectName('myTabs')
# now I call the function that will display
# the gui elements inside this 'Module window'
self.create_module_gui()
self.body.addSubWindow(self.MySubWin)
self.MySubWin.showNormal()
def create_module_gui(self, *args):
module_gui = subwindowGUI.Ui_ModuleWindow()
module_gui.setupUi(module_gui)
self.myTabs.addTab(module_gui, _('New tab'))
self.myTabs.setCurrentWidget(module_gui)
As you can see from the code above my functions are interacting with the main window gui elements. I wanted to move these functions that are related to this specific module into a separate file for the maintaining purposes. That's why I'm asking you to help me on how to achieve that if it's even possible. Thanks in advance, Tomislav.
#Mel:
If I for move those functions into another file:
myFunctions.py
class MyFunctions(object):
def MySubWin(self):
self.MySubWin = QWidget()
self.MySubWin.setObjectName('Module window')
self.myTabs = QtabWidget(self.MySubWin)
self.myTabs.setObjectName('myTabs')
# now I call the function that will display
# the gui elements inside this 'Module window'
self.create_module_gui()
self.body.addSubWindow(self.MySubWin)
self.MySubWin.showNormal()
def create_module_gui(self, *args):
module_gui = subwindowGUI.Ui_ModuleWindow()
module_gui.setupUi(module_gui)
self.myTabs.addTab(module_gui, _('New tab'))
self.myTabs.setCurrentWidget(module_gui)
and then I import that file into my main file.
import myFunctions
class MyApp(QMainWindow, mainGUI.Ui_MainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setupUi(self)
# mainGUI contains QMdiarea in which it opens
# a subwindow by calling a function MySubWin(self)
# QMdiarea name is 'body'
self.OpenSub.triggered.connect(MyFunctions.MySubWin)
What I end up with is the error saying that MyFunctions object has no attribute body.
1st I must say that you won't gain any maintenance out of this ... but for example lets move the create_module_gui to another class
in a new file: creategui.py
class CreateGUI(object):
def create_module_gui(self, *args):
module_gui = subwindowGUI.Ui_ModuleWindow()
module_gui.setupUi(module_gui)
self.myTabs.addTab(module_gui, _('New tab'))
self.myTabs.setCurrentWidget(module_gui)
in your code:
from GUI import mainGUI
from GUI import subwindowGUI
from creategui import CreateGUI
class MyApp(QMainWindow, mainGUI.Ui_MainWindow, CreateGUI):
#yay you have your create_module_gui method now...
Now you can also just put create_module_gui as a function in another file and call it with self as the first param...
See this solution: https://stackoverflow.com/a/47562412/10155767
In your case, don't make a class in myFunctions.py. Instead, define the functions at the top level. Thus myFunctions.py should look like:
def MySubWin(self):
...
def create_module_gui(self, *args):
...
Then in your original file, import the functions within the class like
class MyApp(QMainWindow, mainGUI.Ui_MainWindow):
from myFunctions import MySubWin, create_module_gui
def __init__(self, parent=None):
...
I'm new to python and I have a hard time trying to figuring out how can I inherit from a class in an other module.
module: ~/foo.py
import bar
class foo:
def test(self)
print("this is a test")
module: ~/bar.py
class bar(foo):
def __init__(self):
super().test()
As soon as bar is imported, I get this error message :
NameError: name 'foo' is not defined
If you want to refer to a name in another module then you must import it.
import foo
class bar(foo.foo):
...
This is my code
class Mine:
def __init__(self):
var = "Hello"
def mfx(self):
var += "a method is called"
print var
me = Mine()
when i callme.mfx() it gives the following error
>>> me.mfx()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
me.mfx()
File "D:\More\Pythonnnn\text.py", line 5, in mfx
var += "a method is called"
UnboundLocalError: local variable 'var' referenced before assignment
>>>
I need var only to use inside the class.
So i don't want self.var . Why is this happening?
How can I make a variable which can be used everywhere inside the class.
I am using Python2.7
You should qualify var. (self.var instead of var)
class Mine:
def __init__(self):
self.var = "Hello"
def mfx(self):
self.var += "a method is called"
print self.var
me = Mine()
me.mfx()
You must use self, otherwise you create a local variable that is only accessible inside the method it is created in.
you need to use self to access an instance variable. It's also better to use new style classes and also passed in parameter for your constructor
class Mine(object):
def __init__(self, var):
self.var = var
def mfx(self):
self.var += "a method is called"
print self.var
me = Mine()
me.mfx()
if you don't want to passed "hello" everytime, just create a default value
def __init__(self, var="hello"):
self.var = var