diff --git a/ComplexTreeView.py b/ComplexTreeView.py new file mode 100644 index 0000000..b5e2101 --- /dev/null +++ b/ComplexTreeView.py @@ -0,0 +1,184 @@ +# Reference: http://pythonbeginners.com/python-beginner-tutorial/python-tkinter/tkinter-frames +# Reference: https://stackoverflow.com/questions/34276663/tkinter-gui-layout-using-frames-and-grid +# grid reference: https://stackoverflow.com/questions/34276663/tkinter-gui-layout-using-frames-and-grid + +import os +from tkinter import * +from tkinter import ttk +from tkinter.ttk import * + +import _thread +import pandas as pd +import time + + +class TableViewer(): + def __init__(self, master, newTitle): + self.newWindow = Toplevel(master) + self.newWindow.title(newTitle) + + # declare frames + self.leftframe = ttk.Frame(self.newWindow, width=100, height=300, pad=10) + self.rightframe = ttk.Frame(self.newWindow, width=200, height=300, pad=10) + self.bottomframe = ttk.Frame(self.newWindow, width=300, height=50, pad=5) + + # arrange frames + self.arrangeBottomFrame() + self.arrangeLeftFrameUI() + self.arrangeRightFrameUI() + + # place your widgets(2 frames) into windows + self.leftframe.grid(row=1, column=1) + self.rightframe.grid(row=1, column=2, sticky=W+E+N+S) # sticky="WE" means the inside-objects can extend to west and east + self.rightframe.grid_rowconfigure(0, weight=1) + self.bottomframe.grid(row=2, column=1, sticky="WE", columnspan=2) + + # set a variable of chosen condition + self.currentCondition = "ALL" + + def arrangeBottomFrame(self): + self.lbl_status = ttk.Label(self.bottomframe, text="Count = ") + self.lbl_status.pack(side=LEFT) + + def arrangeRightFrameUI(self): + # configure grid 7*3 + self.rightframe.grid_rowconfigure(0, weight=1) + self.rightframe.grid_rowconfigure(6, weight=1) + self.rightframe.grid_columnconfigure(0, weight=1) + self.rightframe.grid_columnconfigure(2, weight=1) + + + L1 = Label(self.rightframe, text="Display greater than ") + self.ety_Greater = Entry(self.rightframe, width=5) + btn_filter_Greater = ttk.Button(self.rightframe, text="Filter Greater", command=self.filter_greater, width=10) + + L2 = Label(self.rightframe, text="Display less than ") + self.ety_Less = Entry(self.rightframe, width=5) + btn_filter_Less = ttk.Button(self.rightframe, text="Filter Less", command=self.filter_less, width=10) + + btn_showAll = ttk.Button(self.rightframe, text="Show All Data", command=self.showAllData, width=20) + + # arrange each objects, and put objects on 3rd, 4th, 5th row-grid + L1.grid(row=3, column=0) + self.ety_Greater.grid(row=3, column=1) + btn_filter_Greater.grid(row=3, column=2) + + L2.grid(row=4, column=0, sticky=W) + self.ety_Less.grid(row=4, column=1) + btn_filter_Less.grid(row=4, column=2) + + btn_showAll.grid(row=5, columnspan=3) + + + def arrangeLeftFrameUI(self): + # create a TreeView + self.tree = ttk.Treeview(self.leftframe) + self.tree["columns"] = ("Index", "Value") + self.tree.column("Index", stretch=True, width=150) + self.tree.column("Value", stretch=True, width=100) + self.tree.heading("Index", text="Index") + self.tree.heading("Value", text="Value") + + # attach a scrollbar to the frame + treeScroll = ttk.Scrollbar(self.leftframe) + treeScroll.configure(command=self.tree.yview) + self.tree.configure(yscrollcommand=treeScroll.set) + + # read data from file + dataFileDir = "/Users/alumi/PycharmProjects/StocksInfoRetrieval/Data/data_mm.pkl" + if os.path.exists(dataFileDir): + self.tableData = pd.read_pickle(dataFileDir) + self.showAllData() + + # put tree and scroll beside each other in the left frame + self.tree.pack(side=LEFT) + treeScroll.pack(side=LEFT, fill=Y) + + def insertItem2TreeView(self, itemText, values): + ### insert format -> insert(parent, index, iid=None, **kw) + ### reference: https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Treeview + myItemID = self.tree.insert("", "end", text=itemText, values=(values[0], values[1])) + + if myItemID == None: + return False + else: + return True + + def showAllData(self): + # first clear all + self.tree.delete(*self.tree.get_children()) + for i in range(0, self.tableData['HIGH'].size): + self.insertItem2TreeView("HIGH", [self.tableData['HIGH'].index[i], self.tableData['HIGH'].values[i]]) + + self.updateStatusBar() + # print("Tree View Count = " + str(len(self.tree.get_children()))) + + def filter_greater(self): + self.currentCondition = "GREATER" + self.tree.delete(*self.tree.get_children()) + comparedValue = float(self.ety_Greater.get()) + for i in range(0, self.tableData['HIGH'].size): + if (self.tableData['HIGH'].values[i] > comparedValue): + self.insertItem2TreeView("HIGH", [self.tableData['HIGH'].index[i], self.tableData['HIGH'].values[i]]) + + self.updateStatusBar() + # print("Tree View Count = " + str(len(self.tree.get_children()))) + + def filter_less(self): + self.currentCondition = "LESS" + self.tree.delete(*self.tree.get_children()) + comparedValue = float(self.ety_Less.get()) + for i in range(0, self.tableData['HIGH'].size): + if (self.tableData['HIGH'].values[i] < comparedValue): + self.insertItem2TreeView("HIGH", [self.tableData['HIGH'].index[i], self.tableData['HIGH'].values[i]]) + + self.updateStatusBar() + # print("Tree View Count = " + str(len(self.tree.get_children()))) + + def updateTable(self): + print("Current Condition is " + self.currentCondition) + if self.currentCondition == "ALL": + self.showAllData() + elif self.currentCondition == "GREATER": + self.filter_greater() + elif self.currentCondition == "LESS": + self.filter_less() + else: + print("Current Condition has wrong value!!") + + def updateStatusBar(self): + self.lbl_status.config(text="Tree View Count = " + str(len(self.tree.get_children()))) + # print("Tree View Count = " + str(len(self.tree.get_children()))) + + + # test for dynamic update + def addNewData2TableData(self, timestamp): + # print(self.tableData) + newitem = self.tableData.loc["2330 TT Equity"] + newitem.loc["HIGH"] = 10.123 + timestamp + self.tableData.loc["AlumiInsert"+str(timestamp)] = newitem + self.updateTable() + # print(newitem) + + + +######### The following is for testing!!! +def insert_loop(myGUI): + i=0 + while(1): + # myGUI.insertItem2TreeView("Alumi", ["Test", 10]) + myGUI.addNewData2TableData(i) + # myGUI.showAllData() + i += 1 + time.sleep(10) + +if __name__ == '__main__': + _rootWindow = Tk() + myTableViewer = TableViewer(_rootWindow, "Table View") + + try: + _thread.start_new_thread(insert_loop, (myTableViewer, )) + except: + print("Loop of insert is wrong!!\n") + + _rootWindow.mainloop() diff --git a/README.md b/README.md new file mode 100644 index 0000000..1ba1fcc --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# tkinter-mini-projects + +Simple repository for storing Tkinter (Python 3) scripts. + +The name of the file should correspond somewhat to what the script is testing. \ No newline at end of file diff --git a/api_key.dat b/api_key.dat new file mode 100644 index 0000000..cae3126 --- /dev/null +++ b/api_key.dat @@ -0,0 +1 @@ +78056529fa50d02bb671fce91d4359a1 \ No newline at end of file diff --git a/buttons.py b/buttons.py new file mode 100644 index 0000000..e2ba024 --- /dev/null +++ b/buttons.py @@ -0,0 +1,28 @@ +from tkinter import * +from functools import partial + +def add_buttons(): + # Add buttons + for i in range(10): + Button(main, text=str(i), command=partial(print, i)).pack() + + # search for "Add Buttons" Button object and change text and function + for child in main.winfo_children(): + if child.cget('text') == 'Add Buttons': + child.config(text='Delete all buttons') + child.config(command=delete_buttons) + +def delete_buttons(): + # search for buttons and delete all except the 'Delete' Button + for child in main.winfo_children(): + if child.winfo_class() == 'Button': + if child.cget('text') == 'Delete all buttons': + # change "Delete" button text and function + child.config(text='Add Buttons') + child.config(command=add_buttons) + else: + child.destroy() + +main = Tk() +Button(main,text='Add Buttons', command=add_buttons).pack() +main.mainloop() \ No newline at end of file diff --git a/dynamic.py b/dynamic.py new file mode 100644 index 0000000..42f5ee0 --- /dev/null +++ b/dynamic.py @@ -0,0 +1,16 @@ +from tkinter import * +from functools import partial +import string + +buttons = list(string.printable) +print(buttons) +root = Tk() + +def txt(text): + print(text) + +for b in buttons: + btn = Button(root, text=b, command=partial(txt, b)) + btn.pack(side=LEFT,pady=5) + +root.mainloop() \ No newline at end of file diff --git a/excel.py b/excel.py new file mode 100644 index 0000000..c3d09f6 --- /dev/null +++ b/excel.py @@ -0,0 +1,12 @@ +from tkinter import * + +root = Tk() + +height = 5 +width = 5 +for i in range(height): #Rows + for j in range(width): #Columns + b = Entry(root, text="") + b.grid(row=i, column=j) + +mainloop() \ No newline at end of file diff --git a/fetch_http.py b/fetch_http.py new file mode 100644 index 0000000..5852d3b --- /dev/null +++ b/fetch_http.py @@ -0,0 +1,47 @@ +import json, os, sys +from tkinter import * +import requests as r +from functools import partial + +api_url = 'http://api.openweathermap.org/data/2.5/weather?zip={},{}&appid={}' +file = open(os.path.join(sys.path[0], 'api_key.dat'), 'r') +key = file.read() + +def fetch(zc, cc, api): + url = api_url.format(zc, cc, key) + response = r.get(url) + content = response.json() + return content + +class App: + def __init__(self, master): + self.frame1 = Frame(master) + self.frame2 = Frame(master) + + self.outputvar = StringVar() + self.zipvar = StringVar() + + self.zipentry = Entry(self.frame1, textvariable=self.zipvar) + + self.fetchbtn = Button(self.frame1, text="Fetch!", command=lambda:self.fetch(self.zipvar.get())) + self.output = Label(self.frame2, textvariable=self.outputvar, wraplength=300) + + self.frame1.pack() + self.frame2.pack() + + self.zipentry.pack(padx=5,pady=5) + self.fetchbtn.pack(padx=5) + self.output.pack() + + def fetch(self, zipcode): + if zipcode == '': return None + content = fetch(zipcode, 'us', key) + if str(content['cod'])[0] != '2': + print('Unpredicted Status Code Found') + print(content) + print() + return None + self.outputvar.set(content['weather']) +root = Tk() +app = App(root) +root.mainloop() \ No newline at end of file diff --git a/fibonacci.py b/fibonacci.py new file mode 100644 index 0000000..fa8793b --- /dev/null +++ b/fibonacci.py @@ -0,0 +1,38 @@ +from tkinter import * + +x = 1 +y = 1 +z = 0 + +class App: + def __init__(self, master): + frame = Frame(master) + frame.pack() + + self.textVar = StringVar() + + # Lambda Version + # self.button = Button( + # frame, textvariable=self.textVar, command=lambda: self.textVar.set(fibonacci()) + # ) + # self.button.pack() + + # tkinter Version, using separate functions + self.button = Button( + frame, textvariable=self.textVar, command=self.update + ) + self.button.pack() + + def update(self): + self.textVar.set(str(fibonacci())) + +def fibonacci(): + global x, y, z + z = x + x = x + y + y = z + return x + +root = Tk() +app = App(root) +root.mainloop() \ No newline at end of file diff --git a/focus_sample.py b/focus_sample.py new file mode 100644 index 0000000..100d77f --- /dev/null +++ b/focus_sample.py @@ -0,0 +1,30 @@ +from tkinter import * +from tkinter import ttk + +class App: + def __init__(self, root): + self.root = root + self.tree = ttk.Treeview(self.root) #create tree + self.sv = StringVar() #create stringvar for entry widget + self.sv.trace("w", self.command) #callback if stringvar is updated + self.entry = Entry(self.root, textvariable=self.sv) #create entry + self.names = ["Jane", "Janet", "James", "Jamie"] #these are just test inputs for the tree + self.ids = [] #creates a list to store the ids of each entry in the tree + for i in range(len(self.names)): + #creates an entry in the tree for each element of the list + #then stores the id of the tree in the self.ids list + self.ids.append(self.tree.insert("", "end", text=self.names[i])) + self.tree.pack() + self.entry.pack() + def command(self, *args): + self.selections = [] #list of ids of matching tree entries + for i in range(len(self.names)): + #the below if check checks if the value of the entry matches the first characters of each element + #in the names list up to the length of the value of the entry widget + if self.entry.get() != "" and self.entry.get() == self.names[i][:len(self.entry.get())]: + self.selections.append(self.ids[i]) #if it matches it appends the id to the selections list + self.tree.selection_set(self.selections) #we then select every id in the list + +root = Tk() +App(root) +root.mainloop() \ No newline at end of file diff --git a/gradebookFetcher_selectionSet_problem.py b/gradebookFetcher_selectionSet_problem.py new file mode 100644 index 0000000..db3b017 --- /dev/null +++ b/gradebookFetcher_selectionSet_problem.py @@ -0,0 +1,105 @@ +import json, random, datetime, os, faker +from functools import partial +from tkinter import ttk +from tkinter import * + +fake = faker.Faker() + +# Basic Structure of what assignment's data looks like +class Assignment: + def __init__(self): + self.dateDue = fake.date() + self.dateAssigned = fake.date() + self.name = fake.text(max_nb_chars=15)[:-1] + self.category = random.choice(['Daily', 'Major', 'Quiz']) + self.weight = random.choice([1.0, 1.0, random.randint(1, 7) * 0.5]) + self.score = random.choice([100, random.randint(90, 100), random.randint(10, 100)]) + self.totalPoints = 100 + self.weightedTotalPoints = self.weight * self.totalPoints + self.weightedScore = self.weight * self.score + self.percentage = int((self.weightedScore / self.weightedTotalPoints) * 100) + +class Class: + def __init__(self): + self.className = fake.bs() + self.assignments = [Assignment() for _ in range(10)] + +class Window(Frame): + def __init__(self, parent): + Frame.__init__(self, parent) + self.parent = parent + self.init_interface() + + def randomSet(self): + self.choices = [item[1] for item in random.choices(self.treeIDs, k=3)] + self.class_assignments.selection_set(self.choices) + print(self.class_assignments.selection()) + + def assignments_init(self): + self.class_notebook = ttk.Notebook(self.assignments) + self.class_tabs = [] + self.classes = [Class() for _ in range(3)] + + longestName = max([int(max([6.5 * len(assignment.name) for assignment in individualClass.assignments])) for individualClass in self.classes]) + + for classIndex, individualClass in enumerate(self.classes): + # Create a new frame binded to the Class Notebook + class_frame = Frame(self.class_notebook) + + # All the column's in order + columnStrings = ['Date Due', 'Assigned', 'Name', 'Category', 'Weight', 'Score', 'Weighted Score', 'Total Points', 'Weighted Total Points', 'Percentage'] + columnWidths = [80, 80, longestName, 80, 80, 80, 100, 80, 130, 80] + + # Create a new TreeView (table) object + self.class_assignments = ttk.Treeview(class_frame, columns=columnStrings[1:]) + + # Create all the Column's for it + for index, columnString in enumerate(list(columnStrings)): + self.class_assignments.heading('#{}'.format(index), text=columnString) + self.class_assignments.column('#{}'.format(index), minwidth=columnWidths[index], width=columnWidths[index]) + + self.treeIDs = [] + # Insert a assignment with all it's values + for index, assignment in enumerate(individualClass.assignments): + tree_id = self.class_assignments.insert('', 'end', text=assignment.dateDue, values=(assignment.dateAssigned, assignment.name, + assignment.category, assignment.weight, assignment.score, assignment.weightedScore, assignment.totalPoints, + assignment.weightedTotalPoints, '{}%'.format(assignment.percentage))) + self.treeIDs.append((index, tree_id)) + + self.find_worst_button = Button(class_frame, text='Button1', command=partial(self.randomSet, classIndex)) + # self.randomSet() + + for x in range(11): + Grid.columnconfigure(class_frame, x, weight=1) + for y in range(3): + Grid.rowconfigure(class_frame, y, weight=1) + + # Grid the new Finished Table & Buttons + self.class_assignments.grid(column=0, row=0, padx=5, pady=5, columnspan=10) + self.find_worst_button.grid(column=0, row=1, padx=5, pady=5, sticky=N+S+E+W) + + # Add a new tab, using this class's frame for the data + self.class_notebook.add(class_frame, text=individualClass.className) + self.class_tabs.append(class_frame) + + self.class_notebook.grid(column=0, row=0) + + def init_interface(self): + # Window Configurations + self.parent.title("Gradebook Fetcher") + self.parent.config(background="lavender") + + # Notebook for displaying tabs + self.notebook = ttk.Notebook(self.parent) + self.assignments = Frame(self.notebook) + self.assignments_init() + self.notebook.add(self.assignments, text='Assignments') + self.notebook.grid(column=0, row=0, padx=5, pady=5) + +def main(): + root = Tk() + x = Window(root) + root.mainloop() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/hello.py b/hello.py new file mode 100644 index 0000000..12da366 --- /dev/null +++ b/hello.py @@ -0,0 +1,7 @@ +from tkinter import * +root = Tk() + +w = Label(root, text="Hello World!") +w.pack() + +root.mainloop() \ No newline at end of file diff --git a/helloworld.py b/helloworld.py new file mode 100644 index 0000000..f40a50a --- /dev/null +++ b/helloworld.py @@ -0,0 +1,23 @@ +from tkinter import * + +class App: + def __init__(self, master): + frame = Frame(master) + frame.pack() + + self.button = Button( + frame, text="QUIT", fg="red", command=frame.quit + ) + self.button.pack(side=LEFT) + + self.hi_there = Button(frame, text="Hello", command=self.say_hi) + self.hi_there.pack(side=LEFT) + + def say_hi(self): + print("Hello World!") + +root = Tk() +app = App(root) + +root.mainloop() +root.destroy() \ No newline at end of file diff --git a/input_fibonacci.py b/input_fibonacci.py new file mode 100644 index 0000000..6a3f840 --- /dev/null +++ b/input_fibonacci.py @@ -0,0 +1,64 @@ +from tkinter import * +import os, sys, ctypes + +class App: + def __init__(self, master): + frame1 = Frame(master) + frame1.master.title("Fibonacci") + frame1.pack() + frame2 = Frame(master) + frame2.pack() + + # Declare textVar for textbox + self.textVar = StringVar() + self.textVar.set("2") + + # Setting up textbox, plus/minus buttons and a update button + self.entry = Entry(frame2) + self.entry.insert(0,"1") + self.label = Label(frame1, textvariable=self.textVar) + self.flabel = Label(frame2, text="nth=") + self.ubutton = Button(frame2, text = "Update", command=self.fibonacci) + self.pbutton = Button(frame2, text="+", command=self.plus) + self.mbutton = Button(frame2, text="-", command=self.minus) + + # Pack everything + self.label.pack(side=LEFT, padx=5) + self.flabel.pack(side=LEFT, pady=5) + self.entry.pack(side=LEFT, pady=5, padx=(0,5)) + self.ubutton.pack(side=LEFT, pady=5, padx=(5,0)) + self.pbutton.pack(side=LEFT, pady=5) + self.mbutton.pack(side=LEFT, pady=5, padx=(0,5)) + + # Adds one to the textbox's integer then updates the Label + def plus(self): + string = self.entry.get() + self.entry.delete(0, END) + self.entry.insert(0, str(int(string) + 1)) + self.fibonacci() + + # Takes away one from the textbox's integer then updates the Label + def minus(self): + string = self.entry.get() + self.entry.delete(0, END) + self.entry.insert(0, str(int(string) - 1)) + self.fibonacci() + + # Sets the text of the Label to nth integer of the Fibonacci sequence + # Supports negatives + def fibonacci(self): + n = self.entry.get() + negative = int(n) < 0 + x = 1;y = 1;z = 0 + for _ in range(abs(int(n))): + z = x + x = x + y + y = z + if negative: x *= -1 + self.textVar.set(str(x)) + +root = Tk() +root.iconbitmap(os.path.join(sys.path[0], 'img', 'ico.ico')) +root.resizable(False, False) +app = App(root) +root.mainloop() \ No newline at end of file diff --git a/key_click_events.py b/key_click_events.py new file mode 100644 index 0000000..4257cff --- /dev/null +++ b/key_click_events.py @@ -0,0 +1,33 @@ +from tkinter import * + +# I have no honest idea of what is going on here, but it works, so that's cool. + +class Application(Frame): + def __init__(self, master): + Frame.__init__(self, master) + self.master.minsize() + self.master.config() + + self.labelvar = StringVar() + self.master.bind('', lambda event:self.met(event)) + # Bind seems to pass an event, lambda can handle it and pass this event to a def + self.frame = Frame() # Frame within Frame? Hmm? + self.frame.pack(fill='both', expand=True) + self.label = Label(self, textvariable=self.labelvar) # Label for Keyboard String + self.label.pack() + self.pack() + + # Handles keyboard updates, passes then to key(event) for printing without flush + def met(self, event): + self.key(event) + self.labelvar.set(event.keysym) + + + @staticmethod + def key(event): + print(event.keysym, end=' ', flush=True) + +root = Tk() +root.wm_attributes("-topmost", 1) +app = Application(root) +root.mainloop() \ No newline at end of file diff --git a/keyboard_events.py b/keyboard_events.py new file mode 100644 index 0000000..6ea3da4 --- /dev/null +++ b/keyboard_events.py @@ -0,0 +1,20 @@ +import tkinter as tk + +root = tk.Tk() + +def key(event): + print("pressed", repr(event.char)) + +def callback(event): + frame.focus_set() + print("clicked at", event.x, event.y) + +frame = tk.Frame(root, width=100, height=100) +label = tk.Label(frame, text="Help") +frame.bind("", key) +frame.bind("", callback) +frame.pack() +label.pack() + + +root.mainloop() \ No newline at end of file diff --git a/listbox.py b/listbox.py new file mode 100644 index 0000000..618f05e --- /dev/null +++ b/listbox.py @@ -0,0 +1,21 @@ +from tkinter import * + + + +root = Tk() +frame = Frame(root) +listbox = Listbox(frame) + +def callback(event): + print('Callback', event) + listbox.delete(ACTIVE) + +frame.bind("", callback) +frame.pack() +listbox.pack() + +for i in range(20): + listbox.insert(END, str(i)) + + +root.mainloop() \ No newline at end of file diff --git a/msgbox.py b/msgbox.py new file mode 100644 index 0000000..df748d6 --- /dev/null +++ b/msgbox.py @@ -0,0 +1,42 @@ +from tkinter import * +import ctypes, random + +user32 = ctypes.windll.user32 +monitor_x,monitor_y = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1) +print(monitor_x, monitor_y) + +class Demo1: + def __init__(self, master): + self.master = master + self.frame = Frame(self.master) + self.button1 = Button(self.frame, text = 'New Window', width = 25, command = self.new_window) + self.button1.pack() + self.frame.pack() + + def new_window(self): + for x in range(1000): + global monitor_x, monitor_y + self.newWindow = Toplevel(self.master) + width, height, xoffset, yoffset = 500, 150, random.randint(0, monitor_x), random.randint(0, monitor_y) + self.newWindow.geometry("%dx%d%+d%+d" % (width, height, xoffset, yoffset)) + self.app = Demo2(self.newWindow) + +class Demo2: + def __init__(self, master): + self.master = master + self.frame = Frame(master) + self.quitButton = Button(self.frame, text = 'Quit', command = self.close_windows) + self.quitButton.pack() + self.frame.pack() + + def close_windows(self): + self.master.destroy() + +def main(): + root = Tk() + root.geometry = ("+{}+{}".format(monitor_x, monitor_y)) + app = Demo1(root) + root.mainloop() + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/notebook.py b/notebook.py new file mode 100644 index 0000000..8438339 --- /dev/null +++ b/notebook.py @@ -0,0 +1,29 @@ +from tkinter import ttk +from tkinter import * +import random, string + + +gen = lambda length, sample=string.ascii_letters : ''.join(random.choices(list(sample), k=length)) + +class Window(Frame): + def __init__(self, master=None): + self.master = master + + # Master Notebook + n = ttk.Notebook(root) + tabs = [] + + for x in range(1, 21): + tab = ttk.Frame(n) + label = Label(tab, wraplength=500, text=gen(500)) + tabs.append((tab, label)) + + label.pack() + n.add(tabs[-1][0], text='Tab ' + str(x)) + + n.grid(column=0, row=0) + +if __name__ == "__main__": + root = Tk() + app = Window(root) + root.mainloop() \ No newline at end of file diff --git a/randrange.py b/randrange.py new file mode 100644 index 0000000..99656df --- /dev/null +++ b/randrange.py @@ -0,0 +1,14 @@ +from random import random +import math + +def gen(): + #int(return random()*(16)-12) + return random()*(16)-12 + +top = gen() +bot = gen() + +for _ in range(5000000): + top = max(gen(), top) + bot = min(gen(), bot) +print("bot {} top {}".format(bot, top)) \ No newline at end of file diff --git a/tictactoe.py b/tictactoe.py new file mode 100644 index 0000000..3b9a25b --- /dev/null +++ b/tictactoe.py @@ -0,0 +1,158 @@ +from tkinter import * +import os, sys, random, string + +class App: + def __init__(self, master): + frame1 = Frame(master) + frame2 = Frame(master) + frame3 = Frame(master) + frame4 = Frame(master) + frame1.bind("", self.key) + frame2.bind("", self.key) + frame3.bind("", self.key) + frame4.bind("", self.key) + frame1.pack() + frame2.pack() + frame3.pack() + frame4.pack() + + self.vars = [] + self.marker = ["X", "O"] + self.turn = True #True for p1, False for p2 + self.turnvar = StringVar() + self.turnvar.set("Player " + self.getPlayer()) + for x in range(3): + self.vars.append([]) + for y in range(3): + self.vars[x].append(StringVar()) + self.vars[x][y].set("☐") + + self.btns = [[], [], []] + # Button 1 - Top Left + self.btns[0].append(Button(frame1, textvariable=self.vars[0][0], command=lambda: self.btnUpdate(0,0))) + self.btns[0][0].pack(side=LEFT, pady=5, padx=5) + # Button 2 - Top Middle + self.btns[0].append(Button(frame1, textvariable=self.vars[0][1], command=lambda: self.btnUpdate(0,1))) + self.btns[0][1].pack(side=LEFT, pady=5, padx=5) + # Button 3 - Top Right + self.btns[0].append(Button(frame1, textvariable=self.vars[0][2], command=lambda: self.btnUpdate(0,2))) + self.btns[0][2].pack(side=LEFT, pady=5, padx=5) + # Button 4 - Middle Left + self.btns[1].append(Button(frame2, textvariable=self.vars[1][0], command=lambda: self.btnUpdate(1,0))) + self.btns[1][0].pack(side=LEFT, pady=5, padx=5) + # Button 5 - Middle Middle + self.btns[1].append(Button(frame2, textvariable=self.vars[1][1], command=lambda: self.btnUpdate(1,1))) + self.btns[1][1].pack(side=LEFT, pady=5, padx=5) + # Button 6 - Middle Right + self.btns[1].append(Button(frame2, textvariable=self.vars[1][2], command=lambda: self.btnUpdate(1,2))) + self.btns[1][2].pack(side=LEFT, pady=5, padx=5) + # Button 7 - Bottom Left + self.btns[2].append(Button(frame3, textvariable=self.vars[2][0], command=lambda: self.btnUpdate(2,0))) + self.btns[2][0].pack(side=LEFT, pady=5, padx=5) + # Button 8 - Bottom Middle + self.btns[2].append(Button(frame3, textvariable=self.vars[2][1], command=lambda: self.btnUpdate(2,1))) + self.btns[2][1].pack(side=LEFT, pady=5, padx=5) + # Button 9 - Bottom Right + self.btns[2].append(Button(frame3, textvariable=self.vars[2][2], command=lambda: self.btnUpdate(2,2))) + self.btns[2][2].pack(side=LEFT, pady=5, padx=5) + # Quit Button + self.quit = Button(frame4, text='Quit', command=frame4.quit) + self.quit.pack(side=LEFT, pady=5, padx=5) + # Player Turn Label + self.playerlabel = Label(frame4, textvariable=self.turnvar) + self.playerlabel.pack(side=LEFT, pady=5, padx=5) + + def key(self, event): + print("pressed ", repr(event.char)) + + def cycle(self): + self.turn = not self.turn + + def printboard(self): + for x in self.vars: + for y in x: + print(y.get(), end=' ') + print() + print() + + def getPlayer(self, inverse=False): + if(self.turn): + return self.marker[0] + else: + return self.marker[1] + + def rowSame(self, row): + if len(row) > 1: + cache = row[0] + for x in row: + if x != cache: + return False + cache = x + if(row[0] == '☐'): + return False + return True + + def checkBoard(self): + for row in range(3): + x1, x2, x3, y1, y2, y3 = row, row, row, 0, 1, 2 + if(self.vars[x1][y1].get() == self.vars[x2][y2].get() == self.vars[x3][y3].get()): + self.winningBtns(x1, y1, x2, y2, x3, y3) + return self.vars[x1][y1].get() + + for col in range(3): + x1, x2, x3, y1, y2, y3 = 0, 1, 2, col, col, col + if(self.vars[x1][y1].get() == self.vars[x2][y2].get() == self.vars[x3][y3].get()): + self.winningBtns(x1, y1, x2, y2, x3, y3) + return self.vars[0][col].get() + + x1, x2, x3, y1, y2, y3 = 0, 1, 2, 0, 1, 2 + if(self.vars[x1][y1].get() == self.vars[x2][y2].get() == self.vars[x3][y3].get()): + self.winningBtns(x1, y1, x2, y2, x3, y3) + return self.vars[1][1].get() + + x1, x2, x3, y1, y2, y3 = 0, 1, 2, 2, 1, 0 + if(self.vars[x1][y1].get() == self.vars[x2][y2].get() == self.vars[x3][y3].get()): + self.winningBtns(x1, y1, x2, y2, x3, y3) + return self.vars[1][1].get() + return '☐' + + def winningBtns(self, x1, y1, x2, y2, x3, y3): + x = [self.vars[x1][y1].get(), self.vars[x2][y2].get(), self.vars[x3][y3].get()] + for y in x: + if y == '☐': + return False + print("WinningBtns --- {},{} {},{} {},{}".format(x1, y1, x2, y2, x3, y3)) + self.btns[x1][y1].config(disabledforeground='red') + self.btns[x2][y2].config(disabledforeground='red') + self.btns[x3][y3].config(disabledforeground='red') + + def update(self): + self.printboard() + response = self.checkBoard() + if(response != '☐'): + print("Winner: " + response) + self.disableAll() + else: + self.cycle() + self.turnvar.set("Player " + self.getPlayer()) + + def disableAll(self): + for x in range(3): + for y in range(3): + self.btns[x][y].config(state='disabled') + + # Update game board based on who's turn + def btnUpdate(self, x, y): + self.btns[x][y].config(state="disabled") + self.vars[x][y].set(self.getPlayer()) + self.update() + +root = Tk() +root.wm_attributes("-topmost", 1) +root.overrideredirect(1) # Disable Titlebar +root.iconbitmap(os.path.join(sys.path[0], 'img', 'ico.ico')) # Icon for Application +root.resizable(False, False) #Disable resizing +root.geometry("+1000+500") #Make it appear in the middle + +app = App(root) +root.mainloop() \ No newline at end of file diff --git a/treeview_filter_test.py b/treeview_filter_test.py new file mode 100644 index 0000000..a0311be --- /dev/null +++ b/treeview_filter_test.py @@ -0,0 +1,32 @@ +import tkinter as tk +from tkinter import ttk +import faker, random + +fake = faker.Faker() + +class App(tk.Frame): + def __init__(self, parent): + self.parent = parent + self.tree = ttk.Treeview(self.parent, columns=['Name']) + self.button = tk.Entry(self.parent, ) + self.tree.heading('#0', text='Index') + self.tree.heading('#1', text='Name') + self.tree.column('#0', anchor=tk.CENTER) + self.tree.column('#1', anchor=tk.CENTER) + + self.items = [] + for _ in range(10): + self.items.append(self.tree.insert('', 'end', text=_+1, values=(fake.name()))) + + self.button.grid(column=0, row=0, columnspan=1, rowspan=1, padx=5, pady=5, sticky='NEWS') + self.tree.grid(column=0, row=1, columnspan=3, rowspan=1, padx=5, pady=5) + + def update(self): + print('Update received') + self.tree.detach(random.choice(self.items)) + + +if __name__ == "__main__": + root = tk.Tk() + app = App(root) + root.mainloop() \ No newline at end of file diff --git a/treeview_sample.py b/treeview_sample.py new file mode 100644 index 0000000..2319da1 --- /dev/null +++ b/treeview_sample.py @@ -0,0 +1,75 @@ +''' +Created on Mar 21, 2016 + +@author: Bill Begueradj +''' +import tkinter as Tkinter +from tkinter import ttk + +class Begueradj(Tkinter.Frame): + ''' + classdocs + ''' + def __init__(self, parent): + ''' + Constructor + ''' + Tkinter.Frame.__init__(self, parent) + self.parent=parent + self.initialize_user_interface() + + def initialize_user_interface(self): + """Draw a user interface allowing the user to type + items and insert them into the treeview + """ + self.parent.title("Canvas Test") + self.parent.grid_rowconfigure(0,weight=1) + self.parent.grid_columnconfigure(0,weight=1) + self.parent.config(background="lavender") + + + # Define the different GUI widgets + self.dose_label = Tkinter.Label(self.parent, text = "Dose:") + self.dose_entry = Tkinter.Entry(self.parent) + self.dose_label.grid(row = 0, column = 0, sticky = Tkinter.W) + self.dose_entry.grid(row = 0, column = 1) + + self.modified_label = Tkinter.Label(self.parent, text = "Date Modified:") + self.modified_entry = Tkinter.Entry(self.parent) + self.modified_label.grid(row = 1, column = 0, sticky = Tkinter.W) + self.modified_entry.grid(row = 1, column = 1) + + self.submit_button = Tkinter.Button(self.parent, text = "Insert", command = self.insert_data) + self.submit_button.grid(row = 2, column = 1, sticky = Tkinter.W) + self.exit_button = Tkinter.Button(self.parent, text = "Exit", command = self.parent.quit) + self.exit_button.grid(row = 0, column = 3) + + # Set the treeview + self.tree = ttk.Treeview( self.parent, columns=('Dose', 'Modification date')) + self.tree.heading('#0', text='Item') + self.tree.heading('#1', text='Dose') + self.tree.heading('#2', text='Modification Date') + self.tree.column('#1', stretch=Tkinter.YES) + self.tree.column('#2', stretch=Tkinter.YES) + self.tree.column('#0', stretch=Tkinter.YES) + self.tree.grid(row=4, columnspan=4, sticky='nsew') + self.treeview = self.tree + # Initialize the counter + self.i = 0 + + + def insert_data(self): + """ + Insertion method. + """ + self.treeview.insert('', 'end', text="Item_"+str(self.i), values=(self.dose_entry.get()+" mg", self.modified_entry.get())) + # Increment counter + self.i = self.i + 1 + +def main(): + root=Tkinter.Tk() + d=Begueradj(root) + root.mainloop() + +if __name__=="__main__": + main() \ No newline at end of file diff --git a/treeview_selection_set.py b/treeview_selection_set.py new file mode 100644 index 0000000..31203b8 --- /dev/null +++ b/treeview_selection_set.py @@ -0,0 +1,48 @@ +from tkinter import * +from tkinter import ttk +import string, random, faker + +fake = faker.Faker() + +class App: + def __init__(self, root): + self.root = root + self.tree = ttk.Treeview(self.root, columns=['Integer']) + self.button = Button(root, text='Randomly Choose', command=self.randomSet) + self.button2 = Button(root, text='Randomly Choose2', command=self.randomSet) + self.button1 = Button(root, text='Randomly Choose1', command=self.randomSet) + + # Create values + # rnd = lambda x : ''.join(random.choices(list(string.ascii_letters), k=x)) + self.values = [fake.name() for i in range(1, 30)] + + # Create tree ids and insert values + self.tree.heading('#0', text='String') + self.tree.heading('#1', text='Integer') + self.tree.column('#0', anchor=CENTER) + self.tree.column('#1', anchor=CENTER) + + self.ids = [] + for value in self.values: + tree_id = self.tree.insert("", "end", text=value, values=random.randint(0, len(self.values))) + self.ids.append(tree_id) + + # Grid buttons and tree + self.tree.grid(column=0, row=0, columnspan=3, padx=5, pady=5) + self.button2.grid(column=2, row=1, columnspan=1, padx=5, pady=5, sticky=N+E+W+S) + self.button1.grid(column=1, row=1, columnspan=1, padx=5, pady=5, sticky=N+E+W+S) + self.button.grid(column=0, row=1, columnspan=1, padx=5, pady=5, sticky=N+E+W+S) + + # Selection items randomly + def randomSet(self): + minLength = int(len(self.ids) / 2.0) + self.choices = [] + while len(self.choices) < minLength: + choice = random.choice(self.ids) + if choice not in self.choices: + self.choices.append(choice) + self.tree.selection_set(self.choices) + +root = Tk() +App(root) +root.mainloop() \ No newline at end of file diff --git a/treeview_test.py b/treeview_test.py new file mode 100644 index 0000000..2d48d3a --- /dev/null +++ b/treeview_test.py @@ -0,0 +1,66 @@ +import random, datetime +from tkinter import ttk +from tkinter import * + +class Window(Frame): + def __init__(self, parent): + Frame.__init__(self, parent) + self.parent = parent + self.init_interface() + + def init_interface(self): + # Window Configurations + self.parent.title("Window Title") + self.parent.config(background="lavender") + # self.parent.grid_rowconfigure(0, weight=1) + # self.parent.grid_columnconfigure(0, weight=1) + + # Item Name Area + self.item_label = Label(self.parent, text="Name:", bg="lavender") + self.item_entry = Entry(self.parent) + self.item_label.grid(row=0, column=0, sticky=E, ipadx=2, ipady=2, padx=5, pady=5) + self.item_entry.grid(row=0, column=1, sticky=W, padx=5, pady=5) + + # Doses Area + self.dose_label = Label(self.parent, text="Dose:", bg="lavender") + self.dose_entry = Entry(self.parent) + self.dose_label.grid(row=1, column=0, sticky=E, ipadx=2, ipady=2, padx=5, pady=5) + self.dose_entry.grid(row=1, column=1, sticky=W, padx=5, pady=5) + + # Date Area + self.date_label = Label(self.parent, text="Date Modified:", bg="lavender") + self.date_entry = Entry(self.parent) + self.date_label.grid(row=2, column=0, sticky=E, padx=5, pady=5) + self.date_entry.grid(row=2, column=1, sticky=W, padx=5, pady=5) + + # Button Area + self.submit_button = Button(self.parent, text="Insert", command=self.insert_data) + self.exit_button = Button(self.parent, text = "Exit", command=self.parent.quit) + self.submit_button.grid(row=1, column=2, rowspan=3, padx=5, pady=5, ipadx=15, ipady=15) + self.exit_button.grid(row=1, column=3, rowspan=3, padx=5, pady=5, ipadx=15, ipady=15) + + # Tree View Setup + self.i = 0 + self.tree = ttk.Treeview(self.parent, columns=('Dose', 'Modification Date')) + for index, string in enumerate(['Item', 'Dose', 'Modification Date']): + self.tree.heading('#{}'.format(index), text=string) + self.tree.column('#{}'.format(index), stretch=YES) + self.tree.grid(row=3, column=0, columnspan=4, padx=5, pady=(0, 5)) + + def insert_data(self): + # Require dose entry + time = datetime.datetime.now().strftime("%B %d, %Y %I:%M:%S %p") + if self.date_entry.get() != "": # If timestamp is provided + time = self.date_entry.get() + mg = "{} mg".format(self.dose_entry.get()) + text = "Item_{}".format(self.i) + self.tree.insert('', 'end', text=text, values=(mg, time)) + self.i += 1 + +def main(): + root = Tk() + x = Window(root) + root.mainloop() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/unit2quiz.py b/unit2quiz.py new file mode 100644 index 0000000..aebf62a --- /dev/null +++ b/unit2quiz.py @@ -0,0 +1,41 @@ +from tkinter import * +import random, sys, os, ctypes + +class App: + def __init__(self, master): + self.frame1 = Frame(master) + self.frame2 = Frame(master) + self.frame1.pack() + self.frame2.pack() + + self.query = StringVar() + self.query.set("Question") + + self.label = Label(self.frame1, textvariable=self.query) + self.label.pack(padx=5, pady=5) + + # Quit Button + self.quit = Button(self.frame2, text="Quit", command=self.frame2.quit) + self.quit.pack(padx=5, pady=5) + +root = Tk() +root.wm_attributes("-topmost", 1) +root.overrideredirect(1) # Disable Titlebar +root.iconbitmap(os.path.join(sys.path[0], 'img', 'ico.ico')) # Icon for Application +root.resizable(False, False) #Disable resizing + +# get screen res for windows +app = App(root) + +user32 = ctypes.windll.user32 +x,y = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1) # Monitor Height/Width Tuple +h,w = root.winfo_width(), root.winfo_height() # Window Height/Width Tuple +x,y = x-h, y-w + +print("x","y") +print(x,y) +print("h","w") +print(h,w) + +root.geometry("+{}+{}".format(x//2,y//2)) #Make it appear in the middle +root.mainloop() \ No newline at end of file