Jython classes and variable scope
What I want to know is, how can I create GUI elements using swing inside a Jython class so that they can be referenced from outside the class, and I can use statements like button.setText("Hello")
on an object that was created inside another class. For example:
foo.py:
from javax.swing import *
class Test():
def __init__(self):
frame = JFrame("TEST")
button = JButton("Hey")
frame.add(button)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setSize(300,200)
frame.show()
and then I have another file called somethinge开发者_运维百科lse.py:
from foo import *
run = Test()
If I were to want to change the button text by using run.button.setText("Message")
, how could I organise the Test()
class such that I could change the text from the second file, somethingelse.py
.
Your code is throwing away the references it has to the controls, so you can't access them from anywhere - frame
and button
are local variables, and disappear once __init__
returns.
You should (minimally) make them object members:
class Test():
def __init__(self):
self.frame = JFrame("TEST")
self.button = JButton("Hey")
self.frame.add(button)
# ...
You can then say:
from foo import *
run = Test()
run.button.setText("Message")
精彩评论