How can I make running a command depend on the input of a correct password (Tkinter GUI)?
I created a small GUI in Tkinter/python:
import Tkinter
import tkMessageBox
import os
top = Tkinter.Tk()
top.geometry("400x250")
def root_login(): os.system("gksudo su && sudo su") tkMessageBox.showinfo("Login successful!")
def close_window(): top.destroy()
B = Tkinter.Button(top, text ="Login", command = root_login)
B.pack()
Q = Tkinter.Button(top, text ="Quit", command = close_window)
Q.pack()
top.mainloop()If an incorrect password is given in the gksudo su dialog, the dialogue still shows "Login successful!".
How do I show that the password input was wrong, instead of "Login successful!". I want to create this window as a login screen for the application I'm building.
31 Answer
On the edge of being off-topic, but for the sake of gksudo:
Not sure what you want to achieve, since the GUI does not have any effect on what happens in the terminal :)
Then technically
The problem is that you do not set a condition for tkMessageBox.showinfo("Login successful!") to be executed, so whatever happens in os.system("gksudo su && sudo su"), the next line will be performed.
def root_login(): os.system("gksudo su && sudo su") tkMessageBox.showinfo("Login successful!")How to make it work
First, you shouldn't use os.system any more: Really, really old fashioned.
See below for an alternative coding, using subprocess.check_call:
#!/usr/bin/env python
import subprocess
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
top.geometry("400x250")
def root_login(): try: subprocess.check_call(["gksudo", "su"]) except subprocess.CalledProcessError: tkMessageBox.showinfo("message", "OOOOPS...\nWrong password!") else: tkMessageBox.showinfo("message", "Login successful!")
def close_window(): top.destroy()
B = Tkinter.Button(top, text ="Login", command = root_login)
B.pack()
Q = Tkinter.Button(top, text ="Quit", command = close_window)
Q.pack()
top.mainloop()But again, gksudo su does not have any effect, since you run a GUI :)
Explanation
subprocess.check_call(["gksudo", "su"])
...will raise a subprocess.CalledProcessError in case the password is incorrect, and show the message:
If the password is correct, the message:
will appear.
Note
The try/except/else construction, I did for clarity reasons. The function below does exactly the same, since the function wil "jump" from the line:
subprocess.check_call(["gksudo", "su"])to
tkMessageBox.showinfo("message", "OOOOPS...\nWrong password!")in case, and immediately if, the first one raises the subprocess.CalledProcessError:
def root_login(): try: subprocess.check_call(["gksudo", "su"]) tkMessageBox.showinfo("message", "Login successful!") except subprocess.CalledProcessError: tkMessageBox.showinfo("message", "OOOOPS...\nWrong password!") 9