Okay, I am writing a script that might be impossible to fully explain in words. Therefore, I am going to come up with an example that shows the same problem, so please do not tell me to simply combine the scripts or anything, as I am unable to.

Anyways, I have "MyScript.py" and "MyScriptGUI.py". MyScriptGUI is supposed to be like a library, so let's pretend I am not able to edit its code. MyScriptGUI's code looks like this:

#!/usr/bin/python
# MyScriptGUI.py

class GUIClass:
    
    def __init__(self):
        # create a text area named "textArea"
        # bind the function "OnEnterDown" to the Enter key
        
    def OnEnterDown(self):
        # Call the function 'combine' in MyScript.py

Here is the code for MyScript:

#!/usr/bin/python
# MyScript.py

import random

class MyClass:
    
    def __init__(self):
        self.myNumber = random.randint(1, 10)
        self.myWord = "Hello"
        
    def combine(self): # I want this function to be called when the Enter key is pressed
        phrase = self.myWord+str(self.myNumber)
        print phrase

So, how would I go about calling the 'combine' method in MyScript.py? I cannot create a new instance from within MyScriptGUI.py, since I obviously need to preserve the values of "self.myNumber" and "self.myWord" in order to run the 'combine' method. If I create a new instance, these will be lost.

Any ideas?

EDIT: I figured out that I can do this crudely by passing the 'self' argument to the GUI script, but I would rather not do that unless it is the only way.

Thanks in advance.

Recommended Answers

All 2 Replies

Pass the class instance to the GUI program. An example with all classes in the same program.

import random
 
class GUIClass:
 
    def __init__(self, class_instance):
        # create a text area named "textArea"
        # bind the function "OnEnterDown" to the Enter key
        self.ci = class_instance
        print self.ci.my_number, self.ci.my_word
        print "\n calling on_enter_down() within the class"
        self.on_enter_down()

    def on_enter_down(self):
        # Call the function 'combine' in MyScript.py
        self.ci.combine()
        
class MyClass:
 
    def __init__(self):
        self.my_number = random.randint(1, 10)
        self.my_word = "Hello"
 
    def combine(self): # I want this function to be called when the Enter key is pressed
        phrase = "%s %d" % (self.my_word, self.my_number)
        print phrase

MC = MyClass()
GC = GUIClass(MC)
print "\n calling on_enter_down() outside the class"
GC.on_enter_down()

That's exactly what I needed. Perfect. Thanks woooee, you're a great help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.