Skip to content

Commit e8efdfd

Browse files
committed
tkinter and file handling examples
1 parent 6f64f6b commit e8efdfd

8 files changed

+160
-0
lines changed

gam1537.cur

4.19 KB
Binary file not shown.

nat1059.cur

4.19 KB
Binary file not shown.

texteditor.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""Text Editor Demo
2+
This example is using a single line of text.
3+
The purpose is to read some names from a text file,
4+
sort them and write them back (optionally in same file).
5+
"""
6+
democontent = "Carl Chuck Ann Joe Jack Jill Bill Steve Zach Jude Pat Rick"
7+
# Opening the file with context manager
8+
# (it is closed automatically when 'with' is done)
9+
with open('textfile.txt', mode='w') as file:
10+
# We put the list of names into a file first.
11+
file.write(democontent)
12+
13+
# Opening the file again in read-only mode:
14+
with open('textfile.txt', mode='r') as file:
15+
content = file.read()
16+
17+
# Sorting the names
18+
names = sorted(content.split())
19+
print(names)
20+
21+
# Create a new file to put the sorted names
22+
# (optionally you can put them back in the original file)
23+
with open('textfile_sorted.txt', mode='w') as file:
24+
file.write(' '.join(names))

textfile.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Carl Chuck Ann Joe Jack Jill Bill Steve Zach Jude Pat Rick

textfile_sorted.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Ann Bill Carl Chuck Jack Jill Joe Jude Pat Rick Steve Zach

tkinter_custom_cursor.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""Demonstration of Cursor Shapes in Tkinter
2+
Custom Cursors downloaded from:
3+
http://www.cursors-4u.com/cursor/2017/03/14/starfruit.html
4+
http://www.cursors-4u.com/cursor/2014/03/05/minecraft-diamond-sword.html
5+
The .cur files must be in the same directory as where the script is run.
6+
.cur works only on Windows. Other operating units require different format.
7+
"""
8+
import tkinter as tk
9+
from random import choice
10+
11+
class CursorDemo(tk.Frame):
12+
def __init__(self, master=None):
13+
super().__init__(master)
14+
self.master = master
15+
self.winfo_toplevel().title("Cursor Shapes Demo")
16+
self.pack()
17+
cursors = sorted("arrow man based_arrow_down middlebutton based_arrow_up mouse boat pencil bogosity pirate bottom_left_corner plus bottom_right_corner question_arrow bottom_side right_ptr bottom_tee right_side box_spiral right_tee center_ptr rightbutton circle rtl_logo clock sailboat coffee_mug sb_down_arrow cross sb_h_double_arrow cross_reverse sb_left_arrow crosshair sb_right_arrow diamond_cross sb_up_arrow dot sb_v_double_arrow dotbox shuttle double_arrow sizing draft_large spider draft_small spraycan draped_box star exchange target fleur tcross gobbler top_left_arrow gumby top_left_corner hand1 top_right_corner hand2 top_side heart top_tee icon trek iron_cross ul_angle left_ptr umbrella left_side ur_angle left_tee watch leftbutton xterm ll_angle X_cursor lr_angle".split())
18+
colors = sorted(["snow", "linen", "papaya whip", "mint cream", "azure", "lavender", "beige", "pink", "plum", "honeydew", "light steel blue", "light blue", "pale turquoise", "pale green", "tan", "thistle", "cornflower blue", "cyan", "aquamarine", "gold", "light goldenrod", "sandy brown", "salmon", "wheat", "tomato", "azure"])
19+
for i, cursor in enumerate(cursors):
20+
tk.Label(self, cursor=cursor, text=cursor, bg=choice(colors), relief=tk.RAISED, width=15, padx=15, pady=15).grid(row=(i//8), column=(i%8))
21+
tk.Label(self, cursor='none', text='No Cursor', bg=choice(colors), relief=tk.RAISED, padx=15, pady=15).grid(row=(len(cursors)//8+1), columnspan=8, sticky="ew")
22+
# This is where the custom cursor files are used
23+
try:
24+
tk.Label(self, cursor='@nat1059.cur', text='Starfruit (totally custom, downloaded from http://www.cursors-4u.com)', relief=tk.RAISED, padx=15, pady=15).grid(row=(len(cursors)//8+2), columnspan=8, sticky="ew")
25+
tk.Label(self, cursor='@gam1537x.cur', text='Diamond Sword (totally custom, downloaded from http://www.cursors-4u.com)', relief=tk.RAISED, padx=15, pady=15).grid(row=(len(cursors)//8+3), columnspan=8, sticky="ew")
26+
except tk.TclError:
27+
print("The cursor file was not found")
28+
29+
root = tk.Tk()
30+
app = CursorDemo(master=root)
31+
app.mainloop()

tkinter_embedded_graph.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
"""What this program does:
2+
Creates a GUI application with tkinter
3+
with an embedded 3d graph
4+
that gets updated dynamically by the GUI buttons.
5+
Arrows can be added to and removed from the graph.
6+
Each step and exceptions are printed in console.
7+
"""
8+
from tkinter import *
9+
import matplotlib.pyplot as plt
10+
from mpl_toolkits.mplot3d import Axes3D
11+
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
12+
from random import randrange, choice
13+
#hi how are u?
14+
#hello
15+
# can we put the figure on tkinter?
16+
#wait.
17+
18+
class AppWindow(Frame):
19+
20+
def __init__(self, master):
21+
super().__init__(master)
22+
self.master = master
23+
self.winfo_toplevel().title("Embedded 3D Graph in Tkinter GUI")
24+
self.master.protocol('WM_DELETE_WINDOW', self.close_app)
25+
26+
# Control buttons
27+
self.navbar = Frame(self)
28+
self.navbar.pack(side=TOP)
29+
self.add_button = Button(self.navbar, text='Add Random Arrow', command=self.add_arrow)
30+
self.add_button.pack(side=LEFT)
31+
self.add_button = Button(self.navbar, text='Remove Random Arrow', command=self.remove_arrow)
32+
self.add_button.pack(side=LEFT)
33+
self.quit_button = Button(self.navbar, text='QUIT', command=self.close_app)
34+
self.quit_button.pack(side=LEFT)
35+
36+
# Embedded matplotlib graph on the canvas
37+
self.graph = plt.figure()
38+
self.canvas = FigureCanvasTkAgg(self.graph, master=self)
39+
self.canvas.draw()
40+
self.canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=1)
41+
self.ax = self.graph.add_subplot(111, projection='3d')
42+
self.ax.set_xlim([-9, 9])
43+
self.ax.set_ylim([-9, 9])
44+
self.ax.set_zlim([-9, 9])
45+
self.qarrow, self.qlabel = [], [] # placeholders for quiver arrows and labels
46+
self.colors = ['red', 'blue', 'purple', 'green', 'pink', 'gray', 'black']
47+
print("Graph is fully initialized.")
48+
49+
def add_arrow(self):
50+
"""Create a random quiver arrow"""
51+
rolls = [randrange(-9, 9) for _ in range(3)]
52+
color = choice(self.colors)
53+
self.qarrow.append(self.ax.quiver(0, 0, 0, *rolls, color=color))
54+
self.qlabel.append(self.ax.text(*rolls, str(len(self.qlabel)), fontsize=8, color=color))
55+
print("Creating a random arrow.")
56+
self.canvas.draw()
57+
58+
def remove_arrow(self):
59+
"""Remove a random quiver arrow from plot"""
60+
try:
61+
roll = randrange(0, len(self.qarrow))
62+
self.qarrow[roll].remove()
63+
self.qlabel[roll].remove()
64+
print("Removing a random arrow.")
65+
self.canvas.draw()
66+
except Exception as e:
67+
print("Remove failed, " + str(e))
68+
69+
def close_app(self):
70+
"""Safely close the program."""
71+
print("Quitting the program.")
72+
self.quit()
73+
self.master.destroy()
74+
75+
if __name__ == '__main__':
76+
root = Tk()
77+
AppWindow(root).pack()
78+
root.mainloop()

tkinter_hello_world.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import tkinter as tk
2+
3+
class Application(tk.Frame):
4+
def __init__(self, master=None):
5+
super().__init__(master)
6+
self.master = master
7+
self.pack()
8+
self.create_widgets()
9+
10+
def create_widgets(self):
11+
self.hi_there = tk.Button(self)
12+
self.hi_there["text"] = "Hello World\n(click me)"
13+
self.hi_there["command"] = self.say_hi
14+
self.hi_there.pack(side="top")
15+
16+
self.quit = tk.Button(self, text="QUIT", fg="red",
17+
command=self.master.destroy)
18+
self.quit.pack(side="bottom")
19+
20+
def say_hi(self):
21+
print("hi there, everyone!")
22+
23+
root = tk.Tk()
24+
app = Application(master=root)
25+
app.mainloop()

0 commit comments

Comments
 (0)