Show user a message in python - python

quick question here. Is there a really easy way to show a user a message in like a text box in python? I just need to input a string beforehand so I can show the message after a loop runs. Thanks!
EDIT: Just Windows 8.1 and straight python 2.7

If I'm correct that you want a window to let a user type in some text, then show it back as a message box, then you need two modules, tkMessageBox and Tinker, two standard modules in Python 2.7+.
The following documented code does the above
from Tkinter import *
import tkMessageBox
def getInfo():
#This function gets the entry of the text area and shows it to the user in a message box
tkMessageBox.showinfo("User Input", E1.get())
def quit():
#This function closes the root window
root.destroy()
root = Tk() #specify the root window
label1 = Label( root, text="User Input") #specify the label to show the user what the text area is about
E1 = Entry(root, bd =5) #specify the input text area
submit = Button(root, text ="Submit", command = getInfo) #specify the "submit" button that runs "getInfo" when clicked
quit_button = Button(root, text = 'Quit', command=quit) #specify the quit button that quits the main window when clicked
#Add the items we specified to the window
label1.pack()
E1.pack()
submit.pack(side =BOTTOM)
quit_button.pack(side =BOTTOM)
root.mainloop() #Run the "loop" that shows the windows

Related

Tkinter window closing, but python script stays running

I've tried a variety of things but can't seem to figure this out.
Here's a general overview of my program, which takes an Excel file as an import and outputs a .pdf of charts:
Ask user to enter a file name for the outputted file (using Tkinter textbox input)
Ask user to select the input file (using askopenfilename)
Does a bunch of work with Pandas to analyze data, then plots it with matplotlib and PdfPages
Displays a message with Tkinter that says the file was outputted successfully, along with a "Exit" button, which should end the program, but does not.
Here's #1 (separately, I'm wondering how I could modify this code to accept the "Enter" button instead of having to physically click the button):
root = tk.Tk()
root.title("Enter a file name for the report")
def getOutputFileName():
global outputFileName
outputFileName = textBox.get("1.0",'end-1c')
print(outputFileName)
root.quit()
textBox = Text(root, height=1, width = 25)
textBox.pack()
buttonCommit = Button(root, height=5, width=50, text="After entering a file name, click here.", command=lambda: getOutputFileName())
buttonCommit.pack()
root.mainloop()
root.withdraw()
Here's #2:
filetypes=[("Excel files", ".xlsx .xls")]
file_path = fd.askopenfilename(filetypes=filetypes, title = 'Open the Excel input file')
df = pd.read_excel(file_path) ## Start of Pandas code
#3 shouldn't be relevant as it doesn't use Tkinter whatsoever (plus the .pdf is exporting correctly), so here's #4:
window = tk.Toplevel() ## Here I tried using root = tk.Tk() but learned that Toplevel() needs to be used for windows after the first?
window.Title = "Success!"
window.geometry("250x170")
T = Text(window, height = 5, width = 52)
successText = "Report successfully generated. The .pdf file was saved to the same location from which you ran this program. You may close the program now."
b1 = Button(window, text = "Exit", command = window.destroy) ## This button DOES close the window, but doesn't close the entire program (i.e. my IDE stays running the script until I force stop)
T.pack()
b1.pack()
T.insert(tk.END, successText)
tk.mainloop()
print("End of program.") ## this is for testing - the program never gets here.
Any advice would be amazing. Thank you.

How do I save where I was even if I have escaped the program in tkinter python?

I have been recently trying to make a program that it is saved even if you quit the program
The code
import tkinter as tk
root = tk.Tk()
def disabled():
button["state"] = "disabled"
button = tk.Button(root, text="Click me", command=disabled) # when you click the command will disable it
button["state"] = "normal" # first
button.pack()
root.mainloop()
I want from the button to be disabled even if I have escaped

Button.wait_variable usage in Python/Tkinter

There have already been several topics on Python/Tkinter, but I did not find an answer in them for the issue described below.
The two Python scripts below are reduced to the bare essentials to keep it simple. The first one is a simple Tkinter window with a button, and the script needs to wait till the button is clicked:
from tkinter import *
windowItem1 = Tk()
windowItem1.title("Item1")
WaitState = IntVar()
def submit():
WaitState.set(1)
print("submitted")
button = Button(windowItem1, text="Submit", command=submit)
button.grid(column=0, row=1)
print("waiting...")
button.wait_variable(WaitState)
print("done waiting.")
windowItem1.mainloop()
This works fine, and we see the printout “done waiting” when the button is clicked.
The second script adds one level: we first have a menu window, and when clicking the select button of the first presented item, we have a new window opening with the same as above. However, when clicking the submit button, I don’t get the “Done waiting”. I’m stuck on the wait_variable.
from tkinter import *
windowMenu = Tk()
windowMenu.title("Menu")
def SelectItem1():
windowItem1 = Tk()
windowItem1.title("Item1")
WaitState = IntVar()
def submit():
WaitState.set(1)
print("submitted")
button = Button(windowItem1, text="Submit", command=submit)
button.grid(column=0, row=1)
print("waiting...")
button.wait_variable(WaitState)
print("done waiting")
lblItem1 = Label(windowMenu, text="Item 1 : ")
lblItem1.grid(column=0, row=0)
btnItem1 = Button(windowMenu, text="Select", command=SelectItem1)
btnItem1.grid(column=1, row=0)
windowMenu.mainloop()
Can you explain it?
Inside your SelectItem1 function, you do windowItem1 = Tk(). You shouldn't use Tk() to initialize multiple windows in your application, the way to think about Tk() is that it creates a specialized tkinter.Toplevel window that is considered to be the main window of your entire application. Creating multiple windows using Tk() means multiple main windows, and each one would need its own mainloop() invokation, which is... yikes.
Try this instead:
windowItem1 = Toplevel()

tkinter - open file with button and save filename to variable

I am trying to solve a problem that seems simple, but I cannot figure out how.
I want to create a simple program checking if a certain symbol exists in a text file:
The program starts;
The user clicks a button (inside the window, not in the menu);
A dialog box appears;
The user chooses a text file;
A message box displays the result;
The program closes.
Pretty straightforward, but I cannot find how to save the filename into a variable and then use it for the process. I read so many tutorials and I could not find a solution. Here is the code:
from tkinter import *
from tkinter import filedialog
def clicked():
global filename
filename = filedialog.askopenfile(filetypes=(("Word files","*.docx"),))
window = Tk()
window.geometry()
window.title("My App")
open_file_label = Label(window, text="Open your docx file here:", font=("Arial", 10), padx=5, pady=5)
open_file_label.grid(column=0, row=0)
open_file_button = Button(window, text="Click me", command=clicked, padx=5, pady=5)
open_file_button.grid(column=1, row=0)
window.mainloop()
filename is already a variable that contains the chosen file's contents. Just print(filename) and you'll get your data printed in console.

How do I redirect output of a script to a tkinter window?

I am trying to click a tkinter button to open up a new tkinter window to execute a script within it all the way up to the end with a scroll bar if necessary. However, I have only succeeded this far in getting it to run in multitude of ways in a linux window and not within a tkinter window. Can someone help me with redirecting the output of this script into the toplevel window?
self.button_run = Button(self, text="RUN", width=16, command=self.callpy)
self.button_run.grid(row=25, column=0, columnspan=2, sticky=(W + E + N + S))
def run_robbot(self):
new = Toplevel(self)
new.geometry('500x200')
label = Message(new, textvariable=self.callpy, relief=RAISED)
label.pack()
def callpy(self):
pyprog = 'check_asim.robot'
call(['robot', pyprog])
In the snippet above, if I pass callpy to command in Button it runs the robot script in a linux window. If I replace it to call run_robbot which is what I want and expect, it just pops up a new window with a Message Box without running the same script passed to textvariable. I have tried Enter in place of Message Box as well.
I want callpy to be executed in Toplevel tkinter window at the click of the button. How do I do it? Any tkinter operator is fine as long as it confines to the tkinter window.
If you want to capture the output of the command, you should use subprocess.run(cmd,capture_output=True) instead. Below is an sample code:
import subprocess
from tkinter import *
class App(Tk):
def __init__(self):
Tk.__init__(self)
Button(self, text='Run', command=self.run_robot).pack()
def run_robot(self):
win = Toplevel(self)
win.wm_attributes('-topmost', True)
output = Text(win, width=80, height=20)
output.pack()
output.insert(END, 'Running ....')
output.update()
result = self.callpy()
output.delete(1.0, END)
output.insert(END, result)
def callpy(self):
pyprog = 'check_asim.robot'
return subprocess.run(['robot', pyprog], capture_output=True).stdout
App().mainloop()

Categories