S. GUI - JulTob/Python GitHub Wiki

Tkinter GUI

from tkinter import *

This line must go at the beginning of the program to import the Tkinter library.

window = Tk()
window.title(“Window Title”)
window.geometry(“450x100”)

Creates a window that will act as the display, referred to as “window”, adds a title and defines the size of the window.

label = Label( label.place(x = 30, y = 50)text = “Enter number:”)

Adds text to the screen displaying the message shown.

entry_box = Entry (text = 0)
```label.place(x = 30, y = 50)
Creates a blank entry box. Entry boxes can be used by
the user to input data or used to display output.

```python
output_box = Message(text = 0)

Creates a message box which is used to display an output.

output_box [“bg”] = “red”

Specifies the background colour of the object.

output_box [“fg”] = “white”

Specifies the font colour of the object.

output_box [“relief”] = “raised”

Specifies the style of the box. This can be flat, raised, sunken, grooved and ridged.

list_box = Listbox()

Creates a drop-down list box which can only contain strings.

entry_box [“justify”] = “center”

Specifies the justification of the text in an entry box, but this does not work for message boxes.

button1 = Button(text = “Click here”, command = click)

Creates a button that will run the subprogram “click”.

label.place(x = 50, y = 20, width = 100, height = 25)

Specifies the position in which the object will appear in the window. If the position is not specified the item will not appear in the window.

entry_box.delete(0, END)

Deletes the contents of an entry or list box.

num = entry_box.get()

Saves the contents of an entry box and stores it in a variable called num. This does not work with message boxes.

answer = output_txt[“text”]

Obtains the contents of a message box and stores it in a variable called answer. This does not work with an entry box.

output_txt[“text”] = total

Changes the content of a message box to display the value of the variable total.

window.mainloop()

This must be at the end of the program to make sure it keeps working.

Example:

from tkinter import *

def Call():
  msg = Label(window, text = "You pressed the button")
  msg.place(x = 30, y = 50)
  button["bg"] = "blue"
  button["fg"] = "white"

window = Tk()
window.geometry("350x200")
button = Button(text = "Press me", command = Call)
button.place( x = 30, y = 20, width=120, height=25)
window.mainloop()