Quit function for python 2 - python-2.7

I'm following a tutorial in python 3 but using python 2. In the tutorial the following code is used:
button2 = ttk.Button(self, text="Disagree", command = quit)
When I run the code I get the error:
NameError: global name 'quit' is not defined
Is there an equivalent function I could use in python 2? I tried sys.exit() but that froze the tkinter window rather than just closing it out.

Tkinter wants root.quit(). (root is the root Tkinter object)

Related

Better looking Tkinter File Dialogs for Python 2.7

In my application, the user needs to browse for files. However, the askdirectory from tkFileDialog isn't really comfortable for using and browsing files since it's somewhat outdated.
It looks like this:
What I want to achieve should look like the "default" windows browse dialog. Like this:
(Source https://www.pythontutorial.net/tkinter/tkinter-open-file-dialog/)
I am not sure (since I couldn't find proof) but I remember someone telling me that it looks like this because I am using Python 2.7 and not 3+.
Is that true? Does an alternative exist?
It seems it has something to do with your version, as I have done a bit of research and I am using python 3 with the included tkinter and it shows a normal windows explorer popup. So, if you are using one of the up-to-date versions, it should be the OS' default. (I am unable to test that as python 2 will not work properly on my machine although I can confirm since you are using an older one)
I recreated your case with this code:
from tkinter import *
root = Tk()
filedialog.askdirectory()
root.mainloop()
You can try using askopenfilename(). It displays the standard Open File dialog box.
For example:
from tkinter import *
from tkinter import filedialog as fd
root = Tk()
root.title("Button to open files")
root.geometry("500x500")
def openfd(*args):
askk = askopenfilename()
btn = Button(root, text="Click to open file", command=openfd)
btn.place(x=200, y=200)
root.mainloop()
You can read more about it at https://www.pythontutorial.net/tkinter/tkinter-open-file-dialog/.

Convert Code from CodeSkulptor to PyCharm

I am learning python from coursera. They are using CodeSkulptor(http://www.codeskulptor.org/) as IDE.
I want to write the same program in Pycharm.
I am unaware of inbuilt GUI packages in PyCharm(Python 2.7).
I want to convert below code. Please provide me some useful URL's/Important info.
Here is my code:
# define event handlers for control panel
def foo():print "hello world!!!"
# create frame
f = simplegui.create_frame("Guess The Number",300,300)
f.add_button("Range [0,100)", foo, 150)
f.add_button("Range [0,1000)", foo, 150)
f.add_input("Enter a guess", foo, 150)
You can read the documentation here
https://pypi.python.org/pypi/SimpleGUITk
Instead of
import simplegui
you should use
import simpleguitk as simplegui
Reference: How to integrate SimpleGUI with Python 2.7 and 3.0 shell
Please check this link also

tkinter button to open new window and run script

I have a tkinter button that I want to use to run an existing python script in a new cmd window. How would I do that?
I can get the new cmd window to appear, but how do I run the script in it?
Thanks,
Chris.
Multiline code is more readable if you edit your question to add it (allowed, just mark it as edited and say so in the comment) rather than in a comment.
from Tkinter import *
from sys import executable
from subprocess import Popen, CREATE_NEW_CONSOLE
import os
def delprof(): Popen(["cmd.exe"], creationflags=CREATE_NEW_CONSOLE) `
If you get a console with a prompt, you can run python or do anything else. To run a particular python program, the following works for me (3.4).
from tkinter import *
from subprocess import call
pyprog = 'tem2.py'
def callpy(): call(['python', '-i', pyprog] )
root = Tk()
Button(root, text='Run', command=callpy).pack()
root.mainloop()
When running a program, the console normally disappears when the program ends. To prevent that with a python program, so output can be seen, either put something like
input('hit enter to exit')
at the end of the program or start it with '-i', as I did above. This also allows execution of additional interactive statements to examine the result

Issue with configure_traits when using Enthought Canopy

I was following the tutorial "Writing a graphical applications for scientific programming using TraitsUI
http://code.enthought.com/projects/traits/docs/html/tutorials/traits_ui_scientific_app.html
and tested the following code snippet:
from enthought.traits.api import *
from enthought.traits.ui.api import *
class Camera(HasTraits):
""" Camera object """
gain = Enum(1, 2, 3,
desc="the gain index of the camera",
label="gain", )
exposure = CInt(10,
desc="the exposure time, in ms",
label="Exposure", )
def capture(self):
""" Captures an image on the camera and returns it """
print "capturing an image at %i ms exposure, gain: %i" % (
self.exposure, self.gain )
if __name__ == "__main__":
camera = Camera()
camera.configure_traits()
camera.capture()
If I run this at the command line it works as advertised. A GUI pops up. You adjust the parameters, and when you click "OK" it returns the modified values. But when I run the same code from within the Canopy editor by clicking the run button the default parameters print immediately; then the window pops up. When you then adjust the parameters in the GUI and click "OK" the GUI exits but the new parameter values don't print.
It is as if somehow camera.capture() is running before camera.configure_traits.
First, I would suggest using this newer version of the tutorial: http://docs.enthought.com/traitsui/tutorials/traits_ui_scientific_app.html
The one you linked to references materials for TraitsUI version 3, whereas the one above is for the version you're likely using (version 4). The newer tutorial uses the newer module names, traitsui.api instead of enthought.traits.ui.api for example.
As to why Canopy displays the values immediately, this is the expected behavior when running the program:
if __name__ == "__main__":
camera = Camera()
camera.configure_traits()
camera.capture()
When run as __main__ (i.e., not imported as a module by another script), the script does these three things in order: creates an instance of Camera(), pops up the GUI (configure_traits), and then executes the capture method that prints the current values (which are "1" and "10" by default).
The OK/Cancel buttons are not hooked into setting these values. As a test, try changing the exposure or gain but instead of clicking the buttons, try inspecting these attributes from within Canopy's IPython prompt while the GUI is still open: camera.gain or camera.exposure should return the newly set values.

'PyCObject_Import("cairo", "CAPI")' C++ call yields segfault, 'import cairo' on python works

I am running OSX Lion and trying to import the python module for goocanvas, using python2.7.
I managed to successfully compile pygoocanvas-0.14.1, but when I try to import goocanvas through the python2.7 console, I get a segfault. After some debugging, I'm led to this code:
DL_EXPORT (void)
initgoocanvas (void)
{
PyObject *m, *d;
fprintf(stderr,"init<< \n");
// Pycairo_IMPORT; // XXX removed, it expands to the line below, anyways
Pycairo_CAPI = (Pycairo_CAPI_t*) PyCObject_Import("cairo", "CAPI"); // ADDED XXX
fprintf(stderr,"after import<< \n");
if (Pycairo_CAPI == NULL) {
return;
}
I discovered that the segfault happens when the C++ code of the goocanvas python module tries to import the "cairo" library through PyCObject_Import("cairo", "CAPI"). However, if I try to import the cairo module directly through the python2.7 console via import cairo, it works.
How should I proceed? I have a blind seg fault and no idea on why it happens. Remembering that I managed to compile the python goocanvas module, but it segfaults upon trying to import it on python.
What kind of console are you using? I think gtk/glib has some hooks to enable running the main loop concurrently with the REPL. This means that threads are in use, which may cause crashes if glib.threads_init() was not called.
IMHO this is broken by design, because by just importing glib or any g* module a sane Python program that uses any threads will suddenly start to segfault. Supporting threading should be the default.
In our case, the crash was caused by the logging system of glib which was forwarded to Python without holding the GIL.