I´m trying to execute an external script (named EC.py) by pressing a button on my GUI (named BEN.py) and I want it to be inserted on a list (list1) in my GUI.
My external script (EC.py) is like this:
import scipy
import numpy as np
from scipy import misc
from scipy import ndimage
I = scipy.misc.imread('lena.jpg').astype(int)
J = (I/10)*10
K = J + 10
Print K
and my GUI (BEN.py) code is:
import os
import Tkinter as tk
import ttk
def Execute():
EC.K
list1.insert(END, K)
my button widget:
mybutton = Button(myGUI, text=”Execute Code”, command = Execute).pack()
my output list:
list1 = Listbox(myGUI, height=20, width=80)
Everything goes reasonably fine, except that just by running my GUI code it already reads the EC.py script, before I press the button. What I want is to get this script to run only when I press the button.
I suppose (because you didn't wrote complete source code) you wrote import EC
before calling EC.K
Of course Python produce EC.pyc (compiled version) at startup to optimise multi module imports and validate the syntaxe of all implied modules.
What you want in a way is to have dynamical generated code. EC.py
I don't focused on security issues of this behaviour but the simplest way is to use:
try: execfile ("EC.py")
except Exception,msg:
print msg
raise
Related
I have created two python programs. One in which I am doing all the manipulations like sorting the data in Excel file using xlrd and xlwt. Another is I created a GUI using Tkinter and importing the original Excel file on which I need to do the manipulations
My question is how to add this program for manipulation in Tkinter program so that on click I will get required file with all the manipulations done. Both the programs are working individually
Use the import keyword:
Put both files in the same directory, name them like variables (the name does not start from a number, contain dashes etc. Example: gui.py and operations.py)
Put everything from the operations file (except imports) in a function. Example:
import random
def main():
for x in range(10):
print(random.randint(1,10))
Use the import keyword:
from tkinter import Tk, Button
import operations
tk = Tk()
Button(tk, command=operations.main).pack()
tk.mainloop()
where operations (twice) is the name of your file with a function, minus the .py part, and main - the name of a functon.
There's a different way, a bad one, that's os-specific but does not require the main function. Depending on the OS you could try:
import os
os.system('python3 operations.py')# variation 1
os.system('python operations.py')# variation 2
os.system('py -3 operations.py')# variation 3
Hope that's helpful!
I just moved from Matlab to Python. So I am looking hopefully to re-build my GUI in Matlab Guide with Page Python (only hopeful for better performance for big data)
I designed several Push Buttons and inside the code I try to write the below code just beneath Button1.configure.
I can not take out seop value from this clicked () function although I even define it as global variable. I need seop for whole the program.
self.Button1.configure(text='''Data''')
def clicked():
global seop
from tkinter import filedialog, messagebox
fname = filedialog.askopenfilename (initialdir="C:\Sgty")
import numpy as np
seop = np.loadtxt (fname)
messagebox.showinfo ('Data Import', 'Int')
s1 = self.Button1.configure (command=clicked, text="Import Data")
I am working on a program that allows me to directly edit a word document through a tkinter application. I am trying to link the tkinter input from my gui file to my main file so that I can execute my docx functions. When I try to execute my code this way, it tells me that entry in entry.get() is not defined. When I try to import this from main, I receive a circular import error.
main.py
from docx import Document
from docx.shared import Inches
import os
os.chdir("\\Users\\insanepainz\Desktop")
doc = Document('TemplateTest.docx')
paragraphs = doc.paragraphs
def WebsiteChange():
website = entry.get()
print(website)
master.quit()
for paragraph in doc.paragraphs:
if '^website' in paragraph.text:
paragraph.text = gui.entry
print(paragraph.text)
doc.save(doc)
pass
gui.py
import main
from tkinter import *
master = Tk()
#------------Web Entry Window
Label(master, text="Website Name: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
submit = Button(master, text="Submit", command=main.WebsiteChange)
submit.grid(row=1)
# Centers the program window
master.eval('tk::PlaceWindow %s center' % master.winfo_pathname(master.winfo_id()))
mainloop()
I have been struggling to understand this concept for awhile. Circular errors are giving me a headache. Any help would be greatly appreciated.
The import mechanism is designed to allow circular imports. But one must remember the following:
The name of the main module created from the startup script is __main__, rather than as its filename minus .py. Any other file importing the startup script must import __main__, not import filename. (Otherwise, a second module based on the startup script will be created with its normal name.)
Execution of the code in a module is paused at each import. The order of initial imports is important as the last module in the chain is the first to be run to completion. Each object within modules must be available when the reference is executed. References within function definitions are not executed during the import process.
Applying the above to your pair, I assume that gui.py is the startup script. Python will immediate create an empty module object as the value of sys.modules['__main__']. Somain.pyshould importgui.pywithimport main as gui(the name change is just for convenience). Within the function definition, you should be able to usegui.entrywithout problem since there will be no attempt to lookupgui.entryuntil the function is called. I suggest addingentry = gui.entryas the first line of the function and usingentry` in the two places needed.
The following pair of files run as desired when tem2.py is run.
# tem2.py
import tem3
a = 3
print(tem3.f())
# tem3.py
import __main__ as tem2
def f():
return tem2.a
Move the definition of entry into a third file and import it in both files.
You can pass the entry to WebsiteChange:
def WebsiteChange(entry):
website = entry.get()
submit = Button(master, text="Submit",
command=lambda e=entry: main.WebsiteChange(e))
Hi I've learning tkinter on python3 and I'm trying to use multithreading on tkinter to open a few windows also base on tkinter, but it seems that it can only open the first window and the second appears only after closing the first window. I use multithreading is to avoid a followed window being blocked by the previous, but it still seems happened. Here's part of my code and I replace the if statements with if something happened:
from tkinter import *# GUI window
import os
import _thread
top = Tk()
top.title("Test")
def pressbutton(count):
if count <= 10:
print(count)
count += 1
if count < 10:
_thread.start_new_thread(pressbutton,(count,))
if something happened:
os.system("python t1.py")
if something happened:
os.system("python t2.py")
startButton =Button(top, text="Start", command=lambda: pressbutton(0))
startButton.grid(column=0, row=1)
t1.py and t2.py are two python files that also build with tkinter. What I'm trying to get is to have several t1 and t2 windows, but only one appears.
I'm newbie in Tkinter. I try to use next code to open a file using tkFileDialog.askopenfilename and then plot something with Matplotlib:
import matplotlib.pyplot as plt
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
file_path = tkFileDialog.askopenfilename()
x = range(10)
plt.plot(x)
plt.show()
After running the above script I get dialog window to open my file. After file selection I get repeated dialog window to open the file and a new window at the bottom of my screen. I know that the problem is because of plt.show(). What happens and how to avoid dialog window reopening? Should I set a Matplotlib backend for my task?
My versions:
Tcl/Tk 8.5.9
Matplotlib 1.3.1
Tkinter $Revision: 81008 $
OS X 10.9.4
I have found two related stackoverflow questions:
pyplot-show-reopens-old-tkinter-dialog and
matplotlib-figures-not-working-after-tkinter-file-dialog
but no answers. It seems that root.destroy() is not working for me.
When run with python test.py, the following seems to work for me:
import matplotlib.pyplot as plt
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
file_path = tkFileDialog.askopenfilename()
root.destroy()
print file_path
x = range(10)
plt.plot(x)
plt.show()
I think it works because the Tk instance for the file dialog is destroyed before matplotlib fires up its own. Interestingly, it also works for me when run from
ipython --pylab=tk
where I would have expected a problem with starting the event loop twice. The canonical solution in this case would be to check if Tk is already running before firing it up (again).
I'm on MacOSX 10.7.5, custom built matplotlib (shouldn't matter).
The only thing I noticed was that after experimenting with this, the touchpad swipe gestures on my Mac no longer work... Looking into this.
Edit
Here is a breakdown of the Tk commands executed by tkFileDialog.askopenfilename():
# breakdown of tkFileDialog.askopenfilename()
import Tkinter as Tk
window = Tk.Tk()
window.withdraw()
w = Tk.Frame(window)
s = w.tk.call('tk_getOpenFile', *w._options({}))
print s
w.destroy()
window.destroy()
When I run this (with python test.py), I get the file open dialog, where I can choose a file. Upon "OK" it prints the file name and exits. This works every time on my system. However, sometimes the 3-finger gestures on my touchpad stop working while running this program! And they don't come back after the program exits!! Not even after I kill the terminal the program was running in!!!
The only way I found to bring them back is to add the following matplotlib code to test.py:
import matplotlib
matplotlib.use('tkagg')
import matplotlib.pyplot as plt
plt.figure() # simplified from plt.plot(range(10))
plt.show()
and then click on the title bar of "Figure 1". This instantly brings back the 3-finger gestures. I suspect this is simply a bug in Tkinter. (I'm on Tcl/Tk 8.5, by the way)
I cannot reproduce the behavior that the file open dialog is constantly relaunched on my system.
Could you please describe what happens on your system if you launch test.py, without any matplotlib commands?
Alternatively, since Tkinter is old and apparently buggy, may I suggest to use Qt instead? Not only does it look much nicer, it is also snappier and I didn't have any problems with bugs.
Edit 2
I have broken down the Tk actions that matplotlib takes when executing the above commands in a non-interactive environment (i.e. with python test.py and not from iPython). These are the essential backend calls:
import matplotlib.backends.backend_tkagg as backend
figManager = backend.new_figure_manager(1)
figManager.show()
backend.show.mainloop()
These are still backend independent. I.e., for a Qt figure, simply use:
import matplotlib.backends.backend_qt4agg as backend
If we break this down further to the backend-specific layer, we have:
import matplotlib.backends.backend_tkagg as backend
import Tkinter as Tk
window = Tk.Tk()
window.withdraw()
# uncomment this to use the same Tk instance for tkFileDialog and matplotlib
#import tkFileDialog
#fname = tkFileDialog.askopenfilename(master=window)
#print fname
# figManager = backend.new_figure_manager(1)
from matplotlib.figure import Figure
figure = Figure()
canvas = backend.FigureCanvasTkAgg(figure, master=window)
figManager = backend.FigureManagerTkAgg(canvas, 1, window)
# figManager.show()
window.deiconify()
# backend.show.mainloop()
Tk.mainloop()
First, run with the tkFileDialog calls commented out and check if the matplotlib figure appears and behaves correctly. Then uncomment the tkFileDialog calls and see if you finally get the expected behavior.
If not, one has to continue breaking down FigureCanvasTkAgg and FigureManagerTkAgg to understand what is going on...
Edit 3
OK, since the problem persisted, let's break down matplotlib's Tk calls even further. The following code completely isolates all of matplotlib's Tk actions that I consider essential (so it is no longer necessary to import anything from matplotlib!). Note that I left out generating the toolbar and assigning lots of callbacks and keypress events. If the code below works now, then the problem lies with these. If it doesn't work, we can conclude that it is purely a Tk problem, and most likely a bug that should be reported. Here is the code:
import Tkinter as Tk
window = Tk.Tk()
window.withdraw()
# uncomment this to use the same Tk instance for tkFileDialog and matplotlib
#w = Tk.Frame(window)
#fname = w.tk.call('tk_getOpenFile', *w._options({}))
#print fname
#w.destroy()
# canvas = backend.FigureCanvasTkAgg(figure, master=window)
_tkcanvas = Tk.Canvas(master=window, width=640, height=480, borderwidth=4)
_tkphoto = Tk.PhotoImage(master=_tkcanvas, width=640, height=480)
_tkcanvas.create_image(320, 240, image=_tkphoto)
_tkcanvas.focus_set()
# figManager = backend.FigureManagerTkAgg(canvas, 1, window)
window.wm_title("Figure 1")
window.minsize(480, 360)
_tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
# figManager.show()
window.deiconify()
# backend.show.mainloop()
Tk.mainloop()
Please play around with commenting out some lines and see if you can get it working correctly. If not, I would conclude that this is a bug in Tkinter, which should be reported.