diff options
Diffstat (limited to 'test')
-rw-r--r-- | test/README.txt | 1 | ||||
-rw-r--r-- | test/database.py | 36 | ||||
-rw-r--r-- | test/double-click.py | 34 | ||||
-rw-r--r-- | test/fill-vs-expand.py | 11 | ||||
-rw-r--r-- | test/fixratio.py | 33 | ||||
-rw-r--r-- | test/frames.py | 16 | ||||
-rw-r--r-- | test/logs.py | 63 | ||||
-rw-r--r-- | test/optionmenu.py | 30 | ||||
-rw-r--r-- | test/overlapping-widgets.py | 33 | ||||
-rw-r--r-- | test/placeholder.py | 24 | ||||
-rw-r--r-- | test/ptest.sql | 53 | ||||
-rw-r--r-- | test/resizable-image.py | 84 | ||||
-rw-r--r-- | test/table.py | 49 |
13 files changed, 467 insertions, 0 deletions
diff --git a/test/README.txt b/test/README.txt new file mode 100644 index 0000000..72a96ff --- /dev/null +++ b/test/README.txt @@ -0,0 +1 @@ +Just randomly testing stuff used in my main application. diff --git a/test/database.py b/test/database.py new file mode 100644 index 0000000..38b4f70 --- /dev/null +++ b/test/database.py @@ -0,0 +1,36 @@ +from tkinter.messagebox import showerror +from getpass import * +from mysql.connector import connect, Error + +def initialize_db(): + + with connect(host="localhost", user=getuser(), password='') as connection: + with connection.cursor() as cursor: + + cursor.execute('SHOW DATABASES') + for dbs in cursor.fetchall(): + if 'ptest' in dbs: + break + else: + print('createing') + cursor.execute("CREATE DATABASE ptest") + + cursor.execute("USE ptest") + + cursor.execute('SHOW TABLES') + for tables in cursor.fetchall(): + if 'records' in tables: + break + else: + cursor.execute("""CREATE TABLE records( + id INT(3) AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(50), type VARCHAR(4) + )""") + + cursor.execute("DESCRIBE records") + print(cursor.fetchall()) + +try: + initialize_db() +except Error as e: + showerror(title='Oops!', message=e) diff --git a/test/double-click.py b/test/double-click.py new file mode 100644 index 0000000..a2d178e --- /dev/null +++ b/test/double-click.py @@ -0,0 +1,34 @@ +from tkinter import * +from tkinter import messagebox +from tkinter.ttk import * + +def doubleClick(event): + e = event.widget # Get event controls + iid = e.identify("item",event.x,event.y) # Get the double-click item id + state = e.item(iid,"text") # Get state + city = e.item(iid,"values")[0] # Get city + outputStr = "{0} : {1}".format(state,city) # Formatting + messagebox.showinfo("Double Clicked",outputStr) # Output + +root = Tk() +root.title("ch18_12") + +stateCity = {"Illinois": "Chicago", "California": "Los Angeles", + "Texas": "Houston", "Washington": "Seattle", + "Jiangsu": "Nanjing", "Shandong": "Qingdao", + "Guangdong": "Guangzhou", "Fujian": "Xiamen"} + +# Create Treeview +tree = Treeview(root,columns=("cities")) +# Create column headings +tree.heading("#0",text="State") # Icon bar +tree.heading("cities",text="City") +# Format field +tree.column("cities",anchor=CENTER) +# Create Content +for state in stateCity.keys(): + tree.insert("",index=END,text=state,values=stateCity[state]) +tree.bind("<Double-1>",doubleClick) # Double-click binding doubleClick method +tree.pack() + +root.mainloop() diff --git a/test/fill-vs-expand.py b/test/fill-vs-expand.py new file mode 100644 index 0000000..6793214 --- /dev/null +++ b/test/fill-vs-expand.py @@ -0,0 +1,11 @@ +#!/bin/python2 + +import tkinter as tk + +root = tk.Tk() +root.geometry('200x200+200+200') + +tk.Label(root, text='Label', bg='green').pack(expand=False, fill=tk.Y) +tk.Label(root, text='Label2', bg='red').pack(expand=True, fill=tk.BOTH) + +root.mainloop() diff --git a/test/fixratio.py b/test/fixratio.py new file mode 100644 index 0000000..a9393cd --- /dev/null +++ b/test/fixratio.py @@ -0,0 +1,33 @@ +import tkinter as tk +WIDTH, HEIGHT = 400, 300 # Defines aspect ratio of window. + +def maintain_aspect_ratio(event, aspect_ratio): + """ Event handler to override root window resize events to maintain the + specified width to height aspect ratio. + """ + if event.widget.master: # Not root window? + return # Ignore. + + # <Configure> events contain the widget's new width and height in pixels. + new_aspect_ratio = event.width / event.height + + # Decide which dimension controls. + if new_aspect_ratio > aspect_ratio: + # Use width as the controlling dimension. + desired_width = event.width + desired_height = int(event.width / aspect_ratio) + else: + # Use height as the controlling dimension. + desired_height = event.height + desired_width = int(event.height * aspect_ratio) + + # Override if necessary. + if event.width != desired_width or event.height != desired_height: + # Manually give it the proper dimensions. + event.widget.geometry(f'{desired_width}x{desired_height}') + return "break" # Block further processing of this event. + +root = tk.Tk() +root.geometry(f'{WIDTH}x{HEIGHT}') +root.bind('<Configure>', lambda event: maintain_aspect_ratio(event, WIDTH/HEIGHT)) +root.mainloop() diff --git a/test/frames.py b/test/frames.py new file mode 100644 index 0000000..8870fa7 --- /dev/null +++ b/test/frames.py @@ -0,0 +1,16 @@ +import tkinter +from tkinter import * +root = tkinter.Tk() +root.geometry("1920x1080") + +TopFrame = Frame(root, width=1920, height=200, bg= "green") +MiddleRightFrame = Frame(root, width=1120, height=730, bg="orange") +MiddleLeftFrame = Frame(root, width=800, height=730, bg="black") +BottomFrame = Frame(root, width=1920, height=150, bg="blue") + +TopFrame.pack(side=TOP) +BottomFrame.pack(side=BOTTOM) +MiddleRightFrame.pack(side=RIGHT) +MiddleLeftFrame.pack(side=LEFT) + +root.mainloop() diff --git a/test/logs.py b/test/logs.py new file mode 100644 index 0000000..6e602be --- /dev/null +++ b/test/logs.py @@ -0,0 +1,63 @@ +#!/bin/python2 + +import Tkinter +import logging +import datetime + +# this item "module_logger" is visible only in this module, +# (but you can create references to the same logger object from other modules +# by calling getLogger with an argument equal to the name of this module) +# this way, you can share or isolate loggers as desired across modules and across threads +# ...so it is module-level logging and it takes the name of this module (by using __name__) +# recommended per https://docs.python.org/2/library/logging.html +module_logger = logging.getLogger(__name__) + +class simpleapp_tk(Tkinter.Tk): + def __init__(self,parent): + Tkinter.Tk.__init__(self,parent) + self.parent = parent + + self.grid() + + self.mybutton = Tkinter.Button(self, text="ClickMe") + self.mybutton.grid(column=0,row=0,sticky='EW') + self.mybutton.bind("<ButtonRelease-1>", self.button_callback) + + self.mytext = Tkinter.Text(self, state="disabled") + self.mytext.grid(column=0, row=1) + + def button_callback(self, event): + now = datetime.datetime.now() + module_logger.info(now) + +class MyHandlerText(logging.StreamHandler): + def __init__(self, textctrl): + logging.StreamHandler.__init__(self) # initialize parent + self.textctrl = textctrl + + def emit(self, record): + msg = self.format(record) + self.textctrl.config(state="normal") + self.textctrl.insert("end", msg + "\n") + self.flush() + self.textctrl.config(state="disabled") + +if __name__ == "__main__": + + # create Tk object instance + app = simpleapp_tk(None) + app.title('my application') + + # setup logging handlers using the Tk instance created above + # the pattern below can be used in other threads... + # ...to allow other thread to send msgs to the gui + # in this example, we set up two handlers just for demonstration (you could add a fileHandler, etc) + stderrHandler = logging.StreamHandler() # no arguments => stderr + module_logger.addHandler(stderrHandler) + guiHandler = MyHandlerText(app.mytext) + module_logger.addHandler(guiHandler) + module_logger.setLevel(logging.INFO) + module_logger.info("from main") + + # start Tk + app.mainloop() diff --git a/test/optionmenu.py b/test/optionmenu.py new file mode 100644 index 0000000..47c06d4 --- /dev/null +++ b/test/optionmenu.py @@ -0,0 +1,30 @@ + +from tkinter import * + +ws = Tk() +ws.title('PythonGuides') +ws.geometry('400x300') +ws.config(bg='#F26849') + +def change_width(choice): + choice = variable.get() + dropdown.config(width=choice) + +# width choices available. +width_size = [10, 15, 20, 25, 30] + +# setting variable for Integers +variable = IntVar() + +# creating widget +dropdown = OptionMenu( + ws, + variable, + *width_size, + command=change_width +) +# positioning widget +dropdown.pack(expand=True) + +# infinite loop +ws.mainloop() diff --git a/test/overlapping-widgets.py b/test/overlapping-widgets.py new file mode 100644 index 0000000..a810434 --- /dev/null +++ b/test/overlapping-widgets.py @@ -0,0 +1,33 @@ +import tkinter as tk + +class Example(tk.Frame): + def __init__(self, parent): + tk.Frame.__init__(self, parent) + self.text = tk.Text(self, wrap="word") + self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview) + self.text.configure(yscrollcommand=self.text_yview) + self.vsb.pack(side="right", fill="y") + self.text.pack(side="left", fill="both", expand=True) + + # create an info window in the bottom right corner and + # inset a couple of pixels + self.info = tk.Label(self.text, width=20, borderwidth=1, relief="solid") + self.info.place(relx=1.0, rely=1.0, x=-2, y=-2,anchor="se") + + def text_yview(self, *args): + ''' + This gets called whenever the yview changes. For this example + we'll update the label to show the line number of the first + visible row. + ''' + # first, update the scrollbar to reflect the state of the widget + self.vsb.set(*args) + + # get index of first visible line, and put that in the label + index = self.text.index("@0,0") + self.info.configure(text=index) + +if __name__ == "__main__": + root = tk.Tk() + Example(root).pack(side="top", fill="both", expand=True) + root.mainloop() diff --git a/test/placeholder.py b/test/placeholder.py new file mode 100644 index 0000000..7b425c0 --- /dev/null +++ b/test/placeholder.py @@ -0,0 +1,24 @@ +import tkinter as tk + +root = tk.Tk() + +placeholder = 'Your text here' + +def erase(event=None): + if e.get() == placeholder: + e.delete(0,'end') +def add(event=None): + if e.get() == '': + e.insert(0,placeholder) + +e = tk.Entry(root) +e.pack(padx=10,pady=10) + +dummy = tk.Entry(root) #dummy widget just to see other widget lose focus +dummy.pack(padx=10,pady=10) + +add() +e.bind('<FocusIn>',erase) +e.bind('<FocusOut>',add) + +root.mainloop() diff --git a/test/ptest.sql b/test/ptest.sql new file mode 100644 index 0000000..b2a48d4 --- /dev/null +++ b/test/ptest.sql @@ -0,0 +1,53 @@ +-- MariaDB dump 10.19 Distrib 10.11.2-MariaDB, for Linux (x86_64) +-- +-- Host: localhost Database: ptest +-- ------------------------------------------------------ +-- Server version 10.11.2-MariaDB + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8mb4 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `records` +-- + +DROP TABLE IF EXISTS `records`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `records` ( + `userid` varchar(100) NOT NULL, + `ptype` varchar(4) NOT NULL, + PRIMARY KEY (`userid`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `records` +-- + +LOCK TABLES `records` WRITE; +/*!40000 ALTER TABLE `records` DISABLE KEYS */; +INSERT INTO `records` VALUES +('Akash','ISTP'), +('vikas','INTJ'); +/*!40000 ALTER TABLE `records` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2023-03-25 7:22:23 diff --git a/test/resizable-image.py b/test/resizable-image.py new file mode 100644 index 0000000..f298d3a --- /dev/null +++ b/test/resizable-image.py @@ -0,0 +1,84 @@ +from tkinter import * +from PIL import ImageTk, Image + +# class Content(Frame): +# def __init__(self, master, *pargs): +# Frame.__init__(self, master, *pargs) +# +# def set(self, image_file): +# self.image = Image.open(image_file) +# self.img_copy= self.image.copy() +# self.background_image = ImageTk.PhotoImage(self.image) +# +# self.background = Label(self, image=self.background_image) +# self.background.pack(fill=BOTH, expand=YES) +# self.background.bind('<Configure>', self._resize_image) +# self.background.bind('<Button-1>', self.destruct) +# +# def destruct(self, *pargs): +# self.destroy() +# +# def _resize_image(self, event): +# self.image = self.img_copy.resize((event.width, event.height)) +# self.background_image = ImageTk.PhotoImage(self.image) +# self.background.configure(image=self.background_image) + + +class Content(Canvas): + def __init__(self, master, *pargs): + Canvas.__init__(self, master, *pargs) + + def set(self, image_file): + self.image = Image.open(image_file) + self.img_copy= self.image.copy() + self.background_image = ImageTk.PhotoImage(self.image) + + self.image = self.create_image(0, 0, self.background_image) + self.image.bind('<Configure>', self._resize_image) + self.image.bind('<Button-1>', self.destruct) + + def destruct(self, *pargs): + self.destroy() + + def _resize_image(self, event): + self.image = self.img_copy.resize((event.width, event.height)) + self.background_image = ImageTk.PhotoImage(self.image) + self.background.itemconfigure(self.image, image=self.background_image) + +root = Tk() +root.geometry('800x450') +file = "assets/most-accurate-test.png" + +image = ImageTk.PhotoImage(Image.open(file)) +canvas = Canvas(root) +canvas.pack(fill='both', expand=TRUE) + +image_id = canvas.create_image(0, 0, image=image, anchor='nw') +def resizer(e): + global image1, resized_image, new_image + image1 = Image.open(file) + resized_image = image1.resize((e.width, e.height), Image.Resampling.LANCZOS) + new_image = ImageTk.PhotoImage(resized_image) + canvas.itemconfigure(image_id, image=new_image) + +def change(e): + global image1, resized_image, new_image, canvas, image, file + file = "assets/types.png" + image = ImageTk.PhotoImage(Image.open(file)) + print(canvas.winfo_width(), canvas.winfo_height()) + image1 = Image.open(file) + resized_image = image1.resize((canvas.winfo_width(), canvas.winfo_height()), Image.Resampling.LANCZOS) + new_image = ImageTk.PhotoImage(resized_image) + canvas.itemconfigure(image_id, image=new_image) + +canvas.bind('<Configure>', resizer) +canvas.bind('<Button-1>', change) + +# content = Content(root) +# content.set(file) +# content.pack() +# exit() + +root.mainloop() + + diff --git a/test/table.py b/test/table.py new file mode 100644 index 0000000..875d25c --- /dev/null +++ b/test/table.py @@ -0,0 +1,49 @@ +from tkinter import * + +import tkinter as tk +from tkinter import ttk +from tkinter.messagebox import showinfo + +root = tk.Tk() +root.title('Treeview demo') +root.geometry('620x200') + +# define columns +columns = ('first_name', 'last_name', 'email') + +tree = ttk.Treeview(root, columns=columns, show='headings') + +# define headings +tree.heading('first_name', text='First Name') +tree.heading('last_name', text='Last Name') +tree.heading('email', text='Email') + +# generate sample data +contacts = [] +for n in range(1, 100): + contacts.append((f'first {n}', f'last {n}', f'email{n}@example.com')) + +# add data to the treeview +for contact in contacts: + tree.insert('', tk.END, values=contact) + + +def item_selected(event): + for selected_item in tree.selection(): + item = tree.item(selected_item) + record = item['values'] + # show a message + showinfo(title='Information', message=','.join(record)) + + +tree.bind('<<TreeviewSelect>>', item_selected) + +tree.grid(row=0, column=0, sticky='nsew') + +# add a scrollbar +scrollbar = ttk.Scrollbar(root, orient=tk.VERTICAL, command=tree.yview) +tree.configure(yscroll=scrollbar.set) +scrollbar.grid(row=0, column=1, sticky='ns') + +# run the app +root.mainloop() |