Skip to content
Advertisement

Tkinter output to GUI textbox

new to GUI creation with python, I have the following code, how can I make the print command appear on the GUI not the command line? I’m wanting to show the print in the GUI as a text box or some kind of output window so the process can be shown.

import mechanicalsoup
def validateLogin(username, password): #source: https://pythonexamples.org/python-  tkinter-login-form/
    URL3 = 'mysite'
    headers = {
        'referer': URL3 + '/',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
    }
    #print("username entered :", username.get())
    #print("password entered :", password.get())
    browser.open(URL3, headers=headers)     browser.select_form() 
    browser.form.set("username", username.get()) 
    browser.form.set("password", password.get())
    response = browser.submit_selected()
    print(response.text)
    return

#window
tkWindow = Tk()  
tkWindow.geometry('400x150')  
tkWindow.title('Tkinter Login   Form - pythonexamples.org')

#username label and text entry box
usernameLabel =   Label(tkWindow, text="User Name").grid(row=0, column=0)
username = StringVar()
usernameEntry =  Entry(tkWindow, textvariable=username).grid(row=0, column=1)  

#password label and password entry box
passwordLabel =   Label(tkWindow,text="Password").grid(row=1, column=0)  
password = StringVar()
passwordEntry = Entry(tkWindow, textvariable=password, show='*').grid(row=1, column=1)  

validateLogin = partial(validateLogin, username,   password)

#login button
loginButton = Button(tkWindow,  text="Login", command=validateLogin).grid(row=4, column=0)  

tkWindow.mainloop()

Advertisement

Answer

You can add a label for output underneath loginButton:

output = StringVar()
outputLabel = Label(tkWindow, textvariable = output).grid(row = 5, column = 0)

Then replace print(response.text) with output.set(reponse.text) to change the text in your label.

Edit for ScrolledText
Add from tkinter import scrolledtext to the top. Remove output = StringVar() and replace outputLabel = ... with

outputText = scrolledtext.ScrolledText(tkWindow)
outputText.grid(row = 5, column = 0, columnspan = 2)

Then, in validateLogin, replace output.set(...) with

outputText.delete(1.0, "end") #Delete whatever is currently there
outputText.insert(1.0, response.text) #Insert the response
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement