Skip to content

Instantly share code, notes, and snippets.

@CloudCray
Last active August 29, 2015 14:01
Show Gist options
  • Save CloudCray/383bd9e7715f13ac01cc to your computer and use it in GitHub Desktop.
Save CloudCray/383bd9e7715f13ac01cc to your computer and use it in GitHub Desktop.
GUI with TKinter Gists
from Tkinter import * # Python 2
# from tkinter import * # Python 3
class GuiRec(Frame): # We're going to "inherit" the Frame class.
def __init__(self, master, rec): # What happens when you initialize the GuiRec
Frame.__init__(self, master) # Like any frame, you gotta set the parent.
self.record = rec
# You could also make these "public properties" or whatever. Your call.
self.fields = rec.keys()
self.fields.sort() # for now, let's sort these alphabetically
self.labels = []
self.entries = []
# We need to add a row for each key/value pair.
# That means 1 Label and one Entry
for i in range(len(self.fields)):
name = self.fields[i]
lbl = Label(self, text=name)
lbl.grid(column=0, row=i)
self.labels.append(lbl)
entry = Entry(self)
entry.insert(0, rec[name])
entry.grid(column=1, row=i)
self.entries.append(entry)
# Then, we need an "Ok" button
self.btnOk = Button(self, text="OK", command=self.update_record)
self.btnOk.grid(row=len(self.fields), column=0, columnspan=2)
# This is what happens when the Ok button is pressed.
def update_record(self):
rec = {}
for i in range(len(self.record)):
rec[self.fields[i]] = self.entries[i].get() # get the updated value for each key
self.record = rec # update the record
self.master.destroy() # You only want this on popups that end the application
def get_gui_rec(record):
root = Tk() # start a new Tk window as 'root'
window = GuiRec(root, record) # create the GuiRec frame
window.pack() # fill root with the GuiRec window
root.mainloop() # run that ish
new_rec = window.record # once the root window is destroyed, get the GuiRec.record property
return new_rec
from Tkinter import * # Python 2
# from tkinter import * # Python 3
class GuiRec(Frame):
record = {}
def __init__(self, master, rec, header=[], max_row=10):
Frame.__init__(self, master)
self.pack()
self.record = rec
if len(header) == len(rec):
self.fields = header
else:
self.fields = rec.keys()
self.fields.sort()
rec_count = len(self.fields)
columns = int((rec_count - 1) / max_row) + 1
if rec_count > max_row:
rows = max_row
else:
rows = rec_count
self.labels = []
self.entries = []
for i in range(len(self.fields)):
name = self.fields[i]
col = 2 * int(i / max_row)
row = i % max_row
lbl = Label(self, text=name)
lbl.grid(column=col, row=row)
self.labels.append(lbl)
entry = Entry(self)
entry.insert(0, rec[name])
entry.grid(column=(col+1), row=row)
self.entries.append(entry)
self.btnOk = Button(self, text="Return", command=self.get_dict)
self.btnOk.grid(row=rows, column=0, columnspan=columns+1)
def get_dict(self):
rec = {}
for i in range(len(self.record)):
rec[self.fields[i]] = self.entries[i].get()
self.record = rec
self.master.destroy()
def get_gui_rec(record, header=[], max_row=10):
root = Tk()
window = GuiRec(root, record, header=header, max_row=max_row)
root.mainloop()
new_rec = window.record
return new_rec
from Tkinter import * # Python 2
# from tkinter import * # Python 3
import datetime
import threading
class Clock(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.updating = BooleanVar()
self.ValueHour = IntVar()
self.LabelHour = Label(self)
self.LabelHour.grid(row=0, column=0)
self.LabelHourUpdate = Label(self, textvariable=self.ValueHour)
self.LabelHourUpdate.grid(row=0, column=1)
self.ValueMinute = IntVar()
self.LabelMinute = Label(self)
self.LabelMinute.grid(row=1, column=0)
self.LabelMinuteUpdate = Label(self, textvariable=self.ValueMinute)
self.LabelMinuteUpdate.grid(row=1, column=1)
self.ValueSecond = IntVar()
self.LabelSecond = Label(self)
self.LabelSecond.grid(row=2, column=0)
self.LabelSecondUpdate = Label(self, textvariable=self.ValueSecond)
self.LabelSecondUpdate.grid(row=2, column=1)
self.btn_start = Button(self, text="Start", command=self.start)
self.btn_start.grid(row=3, column=0)
self.btn_stop = Button(self, text="Stop", command=self.stop)
self.btn_stop.grid(row=3, column=1)
def start(self):
if not self.updating.get():
self.updating.set(True)
self.new_thread = threading.Thread(target=self.update)
self.new_thread.start()
def stop(self):
self.updating.set(False)
def update(self):
while self.updating.get():
now = datetime.datetime.now()
self.ValueHour.set(now.hour)
self.ValueMinute.set(now.minute)
self.ValueSecond.set(now.second)
root = Tk()
clock = Clock(root)
clock.pack()
root.mainloop()
root = Tk()
clock = Clock(root)
clock.pack()
def hour_forward():
while clock.updating.get():
now = datetime.datetime.now()
clock.ValueHour.set(now.hour + 1)
clock.ValueMinute.set(now.minute)
clock.ValueSecond.set(now.second)
def stop_reset_printbutts():
clock.updating.set(False)
clock.ValueHour.set(0)
clock.ValueMinute.set(0)
clock.ValueSecond.set(0)
print("Butts")
clock.update = hour_forward
clock.btn_stop.config(command=stop_reset_printbutts)
root.mainloop()
import threading, datetime, time
class TimeSet():
running = True
def __init__(self):
self.set = []
self.running = True
def run(self):
while self.running:
if len(self.set) > 20:
self.set.pop(0)
self.set.append(datetime.datetime.now())
time.sleep(1)
ts = TimeSet()
thd = threading.Thread(target=ts.run)
thd.start()
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from PIL import Image, ImageTk
from tkinter import Tk, Label, Frame # Python 3
# from Tkinter import Tk, Label, Frame # Python 2
#############################################################
# Please note that the previous examples were in Python 2 #
#############################################################
import io
class TimeSetPlotter(Frame):
def __init__(self, timeset, master):
Frame.__init__(self, master)
self.pack()
self.label = Label(self)
self.label.pack()
self.timeset = timeset
self.figure = plt.figure()
plt.ylim((0,60))
self.graph = self.figure.add_subplot(111)
self.graph.plot([x.second for x in self.timeset.set])
self.buffer_ = io.BytesIO()
self.figure.savefig(self.buffer_, format="png")
self.buffer_.seek(0) # After saving to a buffer, you need to seek back to the "front"
self.img = Image.open(self.buffer_)
self.photo = ImageTk.PhotoImage(self.img) # This is how we translate a PIL image into something tkinter-friendly
self.label.config(image=self.photo) # use "config" to set properties of tkinter widgets
self.after(500, self.update_image) # setting our super-sexy callback function for 500 ms
def update_image(self):
self.graph.clear() # matplotlib will just keep piling on the plots unless you call this
self.graph.plot([x.second for x in self.timeset.set])
plt.ylim((0,60)) # set the y-axis limits after you call "plot"
self.buffer_.seek(0)
self.figure.savefig(self.buffer_, format="png")
self.buffer_.seek(0)
self.img = Image.open(self.buffer_)
self.photo = ImageTk.PhotoImage(self.img)
self.label.config(image=self.photo)
self.after(50, self.update_image) # make sure this function keeps on running
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment