I am wondering on how to make a very simple gui with the ability for the user to click a button and perform the ability as if it were a user input. (ie raw_input). I would also like it to have the title of the program (game) on top and the ability to exit.

I don't actually know what you mean by "as if it were a user input", but here's how you would make a simple GUI with a exit button, perform button and the title set. Also, for more GUI examples, check out the "Python GUI programming"-topic. Hope this helps!


#Simple GUI example,
#made by Tyyppi_77

    import tkinter as tk
except ImportError:
    import Tkinter as tk

#Your main window
root = tk.Tk()
title = "Put your title here"

def perform():
    #Put your action here

#Create a perform button
p_button = tk.Button(root, text="Do Something", command=perform)
#Show it

#Create an exit button
e_button = tk.Button(root, text="Exit", command=root.destroy)
#Show it

#Start the GUI mainloop

The Tkinter GUI toolkit's equivalent to raw_input() is the Entry widget. Here is an example:

# simple Tkinter code
# using two labels, an entry and a button
# make tk the name space regardless of Python version

    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def action():
    get the entry string
    reverse string using slicing [::-1]
    show the result
    name = enter.get()

# create the root window
root = tk.Tk()
root.title("My title")

# create all the widgets
# the prompt label
label1 = tk.Label(root, text='Enter name:', width=30)
# the entry
enter = tk.Entry(root, bg='yellow')
# the action button
button = tk.Button(root, text='Reverse name', command=action)
# the result label
label2 = tk.Label(root, text='')

# pack widgets vertically in the root window in order

# start cursor in entry

# start the event loop

You exit via the root window upper corner x

Edited 3 Years Ago by bumsfeld

Another option is to use Tkinter's simple dialogs for user input, and to some extent output too:

# use Tkinter's simple dialogs (pop-up) to ask for input
# minvalue and maxvalue are optional

    # for Python2
    import Tkinter as tk
    import tkSimpleDialog as tksd
except ImportError:
    # for Python3
    import tkinter as tk
    import tkinter.simpledialog as tksd

root = tk.Tk()
# show input dialogs without the Tkinter window

# if a non-numeric value is entered, will prompt again
price = tksd.askfloat("Price", "Enter the price of the item:")
# use askfloat or askinteger (whole items only)
quantity = tksd.askinteger("Quantity", "Number of items needed:",
    minvalue=1, maxvalue=1000)

result = "Total cost is %0.2f" % (price*quantity)

# you could use askstring to display the result
sf = "%0.2f" % (price*quantity)
tksd.askstring("Result", "Total cost is:", initialvalue=sf)
This article has been dead for over six months. Start a new discussion instead.