Reputation:
I made a GUI app where you can open a file and then you can calculate some things on it (from the main function). However, when I run this program, it automatically opens the file which I chose and the main() function runs, even if I haven't commanded it yet. Here is the relevant part of the code for now:
from Tkinter import *
import tkFileDialog
import tkMessageBox
import math
import re
class App(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.text = Text()
self.text.pack()
menu = Menu(master)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Open File", command=self.OpenFile)
filemenu.add_command(label="Save File As", command=self.SaveFile)
processmenu = Menu(menu)
menu.add_cascade(label="Calculate", menu=processmenu)
processmenu.add_cascade(label="Process the Input File", command = main())
helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu =helpmenu)
helpmenu.add_command(label="About", command=self.about)
exitmenu = Menu(menu)
menu.add_cascade(label="Quit", menu=exitmenu)
exitmenu.add_command(label="Quit", command=self.quit)
def about(self):
tkMessageBox.showinfo( "About", "Lot Data Calculator v.01"\
"\n Made by Michael Hander."\
"\n Contact him at http://www.twitter.com/sludgehander."\
"\n All Rights Reserved. 2015")
def OpenFile(self):
infile = tkFileDialog.askopenfile()
text = infile.read()
if text != None:
self.text.delete(0.0, END)
self.text.insert(END,text)
def SaveFile(self):
outputfile = tkFileDialog.asksaveasfile()
savethetext = str(self.text.get(0.0,END))
outputfile.write(savethetext)
outputfile.close()
def quit(self):
root.destroy()
def main():
infile = tkFileDialog.askopenfile()
#algorithms to solve the input file
My plan is to open the program and then I can open the file, and then the input shows on the widget below. I have made that, except when I run the program, it doesn't show me the menu and instead an open file dialog shows immediately. And I tried putting the main() in the command of the process menu, but still when I click it, nothing happens. Also, after the main() function is done, I should save it to a new file using the Save File menu but I don't know how to put all of the strings that results.
http://dpaste.com/1BV8YR2 Here is the whole function.
Upvotes: 0
Views: 827
Reputation: 385970
Look at this bit of code:
processmenu.add_cascade(..., command = main())
You are asking python to run the main
function, and whatever it returns is what gets assigned to the command
attribute.
You want to remove the parenthesis so that you are passing a reference to the function, rather than the result of executing the function:
processmenu.add_cascade(..., command = main)
Upvotes: 2