Tkinter: Difference between revisions
(5 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
Tkinter is a Python API for the Tk GUI. It is built into the Python standard library and is cross platform. | Tkinter is a Python API for the Tk GUI. It is built into the Python standard library and is cross platform. | ||
==Layout== | |||
===<code>tk.Frame</code>=== | |||
You can use <code>tk.Frame</code> as general containers. | |||
==Images== | ==Images== | ||
To display an image | To display an image, create a <code>tk.Canvas</code> and then use <code>canvsa.create_image</code>. | ||
{{ hidden | Example | | |||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
import tkinter as tk | import tkinter as tk | ||
Line 27: | Line 33: | ||
canvas.itemconfigure(canvas_image, image=photo_img) | canvas.itemconfigure(canvas_image, image=photo_img) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
}} | |||
;Notes | |||
* Make sure the <code>ImageTk.PhotoImage</code> does not get garbage collected. | |||
==Animation Loop== | |||
For interactive applications, you may want an animation loop called every few milliseconds.<br> | |||
To accomplish this, use <code>.after</code>. | |||
{{ hidden | Example | | |||
<syntaxhighlight lang="python"> | |||
import tkinter as tk | |||
import time | |||
last_time = time.time() | |||
def animation_loop(): | |||
global last_time | |||
now = time.time() | |||
delta_time = now - last_time | |||
print("Time elapsed", delta_time) | |||
last_time = now | |||
window.after(1, animation_loop) | |||
window = tk.Tk() | |||
animation_loop() | |||
window.mainloop() | |||
</syntaxhighlight> | |||
}} | |||
==Keypress== | |||
To just detect key presses: | |||
{{ hidden | Example | | |||
<syntaxhighlight lang="python"> | |||
import tkinter as tk | |||
def key_pressed(event): | |||
print("Key pressed", event.char, event.keysym) | |||
window = tk.Tk() | |||
window.bind("<Key>", key_pressed) | |||
window.mainloop() | |||
</syntaxhighlight> | |||
}} | |||
;Notes | ;Notes | ||
* | * Use <code><KeyRelease></code> to detect key releases. |