I am trying to capture the entry value from the pop up window into a variable that I can access later and manipulate. I need to make a lists of several message box entries to generate questions for the user. However, whenever I try to capture it the variable I assign it to comes up empty.
from tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack()
class popupWindowID (object):
def __init__(self,master):
top=self.top=Toplevel(master)
self.label=Label(top,text="ID")
self.label.pack()
self.entrybox=Entry(top)
self.entrybox.pack()
self.b=Button(top,text='Enter',command=self.cleanup)
self.b.pack()
def cleanup(self): # This cleans it up so it can be overwritten if needed
self.value=str(self.entrybox.get())
self.top.destroy()
class mainWindow(object):
def __init__(self,master):
self.master=master
self.ID=Button(topFrame,text="ID", command=self.popupID)
self.ID.pack(side = TOP)
self.info=Button(topFrame,text="Show Test Information",command=self.entryValue)
self.info.pack(side = TOP)
def popupID(self):
self.ID=popupWindowID(self.master)
self.master.wait_window(self.ID.top)
def entryValue(self):
print(self.ID.value)
m=mainWindow(root)
root.mainloop()
Related
I am using a jupyter notebook in Visual Studio Code.
In normal case when for example running a cell that contains a list or similar
my_test_list : list = [1,2,3]
I get the option Show variable in data viewer in the Window Juyper: Variables
But when I have an objects of one of my own classes:
class MyClass():
def __init__(self,val1,val2):
self.val1 = val1
self.val2 = val2
def __repr__(self):
return f"{self.val1} and {self.val2}"
def __str__(self):
return self.__repr__()
and create a new object in another cell with
myObject = MyClass(1,2)
myObject is shown in the Window Juyper: Variables but no button Show variable in data viewer appears.
My question: Is there any way to define a custom representation of for example MyObject that the data viewer can recognise and display or are there any packages that would allow the data viewer to pick up for example the repr or str method?
Trying the very first example in traitsui doc:
from traits.api import HasTraits, Str, Int
from traitsui.api import View, Item
import traitsui
class SimpleEmployee(HasTraits):
first_name = Str
last_name = Str
department = Str
employee_number = Str
salary = Int
view1 = View(Item(name = 'first_name'),
Item(name = 'last_name'),
Item(name = 'department'))
sam = SimpleEmployee()
sam.configure_traits(view=view1)
makes the Spyder IPython console hang, even after the UI window has been closed.
MacOSX 10.14.6, Spyder 4.0.0, Python 3.7.0, IPython 7.10.2, traitsui 6.1.3
Probably something to configure about the UI event loop, but what and how ?
The difference between the Canopy IPython console and the Spyder IPython console is that
app = QtGui.QApplication.instance()
print(app)
returns
<PyQt5.QtWidgets.QApplication at 0xXXXXXXXX>
for both, but
is_event_loop_running_qt4(app)
returns Truein Canopy IPython terminal and False in Spyder IPython terminal.
It is necessary to patch view_application() in traits.qt4.view_application by commenting out the lines starting a new ViewApplication instance depending on that test. Instead of changing the original file, it is possible to run the following code:
# -*- coding: utf-8 -*-
"""Avoid Spyder console to hang when using configure_traits()
"""
from IPython import get_ipython
from pyface.qt import QtCore, QtGui, qt_api
from pyface.util.guisupport import is_event_loop_running_qt4
from traitsui.api import toolkit
from traitsui.qt4.view_application import ViewApplication
KEEP_ALIVE_UIS = set()
def on_ui_destroyed(object, name, old, destroyed):
""" Remove the UI object from KEEP_ALIVE_UIS.
"""
assert name == 'destroyed'
if destroyed:
assert object in KEEP_ALIVE_UIS
KEEP_ALIVE_UIS.remove(object)
object.on_trait_change(on_ui_destroyed, 'destroyed', remove=True)
def _view_application(context, view, kind, handler, id, scrollable, args):
""" Creates a stand-alone PyQt application to display a specified traits UI
View.
Parameters
----------
context : object or dictionary
A single object or a dictionary of string/object pairs, whose trait
attributes are to be edited. If not specified, the current object is
used.
view : view object
A View object that defines a user interface for editing trait attribute
values.
kind : string
The type of user interface window to create. See the
**traitsui.view.kind_trait** trait for values and
their meanings. If *kind* is unspecified or None, the **kind**
attribute of the View object is used.
handler : Handler object
A handler object used for event handling in the dialog box. If
None, the default handler for Traits UI is used.
scrollable : Boolean
Indicates whether the dialog box should be scrollable. When set to
True, scroll bars appear on the dialog box if it is not large enough
to display all of the items in the view at one time.
"""
if (kind == 'panel') or ((kind is None) and (view.kind == 'panel')):
kind = 'modal'
# !!!!!!! The following 4 lines commented out !!!!!!!!!!!
# app = QtGui.QApplication.instance()
# if app is None or not is_event_loop_running_qt4(app):
# return ViewApplication(context, view, kind, handler, id,
# scrollable, args).ui.result
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
ui = view.ui(context,
kind=kind,
handler=handler,
id=id,
scrollable=scrollable,
args=args)
# If the UI has not been closed yet, we need to keep a reference to
# it until it does close.
if not ui.destroyed:
KEEP_ALIVE_UIS.add(ui)
ui.on_trait_change(on_ui_destroyed, 'destroyed')
return ui.result
def view_application(self, context, view, kind=None, handler=None,
id='', scrollable=None, args=None):
""" Creates a PyQt modal dialog user interface that
runs as a complete application, using information from the
specified View object.
Parameters
----------
context : object or dictionary
A single object or a dictionary of string/object pairs, whose trait
attributes are to be edited. If not specified, the current object is
used.
view : view or string
A View object that defines a user interface for editing trait
attribute values.
kind : string
The type of user interface window to create. See the
**traitsui.view.kind_trait** trait for values and
their meanings. If *kind* is unspecified or None, the **kind**
attribute of the View object is used.
handler : Handler object
A handler object used for event handling in the dialog box. If
None, the default handler for Traits UI is used.
id : string
A unique ID for persisting preferences about this user interface,
such as size and position. If not specified, no user preferences
are saved.
scrollable : Boolean
Indicates whether the dialog box should be scrollable. When set to
True, scroll bars appear on the dialog box if it is not large enough
to display all of the items in the view at one time.
"""
return _view_application(context, view, kind, handler,
id, scrollable, args)
from traitsui.qt4.toolkit import GUIToolkit
GUIToolkit.view_application = view_application
Thus, the behavior is OK in both Spyder and Canopy IPython consoles. Note that configure_traits(kind='modal') is also OK in both.
I'm currently building an accounting app, now I want to persist this "Period End Date" that is changeable. I believe we can use global variable, however I don't know how to do so. What I have tried so far is to create a variable in application.conf like this application.date="2014/12/15".
Moreover, I'm not sure how to change the value using above approach . Is there any good approach for this problem ?
A possible way to go is to use a Singeleton Object which is initialized in the Global.scala.
The Global Object has to go in the scala-root of the application or to be configured through application.conf.
Singleton for shared Data
in app/shared/Shared.scala(the name is free)
package shared
object Shared {
private var data: Int = 0
def setData(d: Int) : Unit = data = 0
def getData : Int = data
}
In application.conf you can set the Global to be called on start of the application (you could also just put a file called Global.scala in app, that would be used by default)
application.global= settings.Global
shared.initial = 42
In app/settings/Global.scala
object Global extends GlobalSettings {
override def onStart(app: Application) {
// Here I use typesafe config to get config data out of application conf
val cfg: Config = ConfigFactory.load()
val initialValue = cfg.getInt(shared.initial)
// set initial value for shared
Shared.setData(initialValue)
}
}
In Play code to get or set the shared data.
import shared.Shared
Shared.getData
Shared.setData( 8 )
I am currently trying to make a traitsUI GUI for a class that contains many instances of a single object. My problem is very similar to the one solved in MultiObjectView Example TraitsUI.
However, I don't like the idea of using a context as it requires me to write out the same view many times for each object I have (and I might have a lot). So I tried to edit the code to make it so that each Instance of the House object would default to looking like its normal view when it is viewed from the Houses object. It almost worked, except now I get a button that takes me to the view I want rather than seeing the views nested in one window (like the output of the TraitsUI example above).
Is there a way to adapt the below to get the desired output? I think I have to further edit the create_editor function but I can find very little documentation on this - only many links to different trait editor factories...
Thanks,
Tim
# multi_object_view.py -- Sample code to show multi-object view
# with context
from traits.api import HasTraits, Str, Int, Bool
from traitsui.api import View, Group, Item,InstanceEditor
# Sample class
class House(HasTraits):
address = Str
bedrooms = Int
pool = Bool
price = Int
traits_view =View(
Group(Item('address'), Item('bedrooms'), Item('pool'), Item('price'))
)
def create_editor(self):
""" Returns the default traits UI editor for this type of trait.
"""
return InstanceEditor(view='traits_view')
class Houses(HasTraits):
house1 = House()
house2= House()
house3 = House()
traits_view =View(
Group(Item('house1',editor = house1.create_editor()), Item('house2',editor = house1.create_editor()), Item('house3',editor = house1.create_editor()))
)
hs = Houses()
hs.configure_traits()
Would something like this work?
It simplifies things a little bit and gives you a view that contains the list of views for your houses.
# multi_object_view.py -- Sample code to show multi-object view
# with context
from traits.api import HasTraits, Str, Int, Bool
from traitsui.api import View, Group, Item,InstanceEditor
# Sample class
class House(HasTraits):
address = Str
bedrooms = Int
pool = Bool
price = Int
traits_view =View(
Group(
Item('address'), Item('bedrooms'), Item('pool'), Item('price')
)
)
class Houses(HasTraits):
house1 = House()
house2= House()
house3 = House()
traits_view =View(
Group(
Item('house1', editor=InstanceEditor(), style='custom'),
Item('house2', editor=InstanceEditor(), style='custom'),
Item('house3', editor=InstanceEditor(), style='custom')
)
)
if __name__ == '__main__':
hs = Houses()
hs.configure_traits()
I am trying to implement manytomany field relation in django-nonrel on mongodb. It was suggessted at to:
Django-nonrel form field for ListField
Following the accepted answer
models.py
class MyClass(models.Model):
field = ListField(models.ForeignKey(AnotherClass))
i am not sure where the following goes, it has been tested in fields.py, widgets,py, models.py
class ModelListField(ListField):
def formfield(self, **kwargs):
return FormListField(**kwargs)
class ListFieldWidget(SelectMultiple):
pass
class FormListField(MultipleChoiceField):
"""
This is a custom form field that can display a ModelListField as a Multiple Select GUI element.
"""
widget = ListFieldWidget
def clean(self, value):
#TODO: clean your data in whatever way is correct in your case and return cleaned data instead of just the value
return value
admin.py
class MyClassAdmin(admin.ModelAdmin):
form = MyClassForm
def __init__(self, model, admin_site):
super(MyClassAdmin,self).__init__(model, admin_site)
admin.site.register(MyClass, MyClassAdmin)
The following Errors keep popping up:
If the middle custom class code is used in models.py
name 'SelectMultiple' is not defined
If custom class code is taken off models.py:
No form field implemented for <class 'djangotoolbox.fields.ListField'>
You just need to import SelectMultiple by the sound of it. You can put the code in any of those three files, fields.py would make sense.
Since it's pretty usual to have:
from django import forms
at the top of your file already, you probably just want to edit the code below to:
# you'll have to work out how to import the Mongo ListField for yourself :)
class ModelListField(ListField):
def formfield(self, **kwargs):
return FormListField(**kwargs)
class ListFieldWidget(forms.SelectMultiple):
pass
class FormListField(forms.MultipleChoiceField):
"""
This is a custom form field that can display a ModelListField as a Multiple Select GUI element.
"""
widget = ListFieldWidget
def clean(self, value):
#TODO: clean your data in whatever way is correct in your case and return cleaned data instead of just the value
return value
You probably also want to try and learn a bit more about how python works, how to import modules etc.