Examples
This section provides practical examples of using TkeXtras, demonstrating how to integrate WidgetsRender and TreeviewDataFrame into your Tkinter projects.
Using WidgetsRender
The WidgetsRender class simplifies widget placement in Tkinter using grid(), pack(), and place() with default layout parameters.
Example usage of WidgetsRender
1"""
2This is a working example of using the WidgetsRender class
3"""
4import tkinter as tk
5from tkinter import ttk
6import requests
7from tkextras import WidgetsRender
8
9
10class ExampleFrame(WidgetsRender, ttk.Frame):
11 """
12 When creating a class, add WidgetsRender to the main parent tk.Widget class
13 """
14
15 def __init__(self, *args, **options):
16
17 super().__init__(*args, **options)
18 self.create_widgets()
19
20 def create_widgets(self):
21 """
22 Placing elements on a form using the rgrid() method
23
24 :return: None
25 """
26 def fetch_quote():
27 """
28 Fetching a random quote from dummyjson.com
29 The attributes of the rendered element are changed dynamically
30
31 :return: None
32 """
33 try:
34 response = requests.get("https://dummyjson.com/quotes/random")
35 res = response.json()
36
37 # The attributes of the rendered element are changed dynamically:
38 quote['text'] = res["quote"]
39 author['text'] = res["author"]
40
41 except ConnectionError:
42
43 # dummyjson.com can be unavailable, then we get a replacement quote:
44 quote['text'] = "This is the great quote!"
45 author['text'] = "Great Author"
46
47 grid = self.rgrid
48 head = ("Helvetica", 13)
49 italic = ("Helvetica", 11, "italic")
50 underline = ("Helvetica", 11, "underline")
51
52 grid(self)
53
54 # there is no need to explicitly create a variable to render an object:
55 grid(tk.Label(self, text="Click the button and get a quote.", font=head), dict(row=0, column=0, columnspan=3))
56
57 # in one command we get a fully rendered object:
58 quote = grid(ttk.Label(self, text="", wraplength=250, font=italic), dict(row=1, column=0, columnspan=3))
59 author = grid(ttk.Label(self, text="", font=underline), dict(row=2, column=0, columnspan=3, sticky="e"))
60
61 grid(tk.Button(self, text=" Fetch Quote! ", command=fetch_quote, font=head), dict(row=3, column=1))
62
63
64app = ExampleFrame(dict(pady=5, padx=2)) # setting a parameter common to all elements (x, y offset)
65app.winfo_toplevel().title("Example WidgetsRender")
66app.mainloop()
Using TreeviewDataFrame
The TreeviewDataFrame`class extends `ttk.Treeview, allowing for seamless integration with Pandas DataFrames.
Example usage of TreeviewDataFrame
1"""
2This is a working example of using the TreeviewDataFrame class
3"""
4import pandas as pd
5from tkinter import ttk
6from tkextras import WidgetsRender, TreeviewDataFrame
7from faker import Faker
8fake = Faker()
9
10
11class ExampleTreeviewDataFrame(WidgetsRender, ttk.Frame):
12 """
13 Example of TreeviewDataFrame class based on the WidgetsRender and ttk.Frame classes
14 """
15 def __init__(self, *args, **options):
16
17 super().__init__(*args, **options)
18 self.create_widgets()
19
20 def create_widgets(self):
21 """
22 Placing elements on a form using the rgrid() method
23
24 :return: None
25 """
26 grid = self.rgrid
27
28 # 1. Prepare a dataframe containing values 0 and 1,
29 # values 1 are changed to tree.svars["flag_symbol"]["check"], 0 to tree.svars["flag_symbol"]["uncheck"]:
30 url = "https://raw.githubusercontent.com/whellcome/MLGliomaClassification/master/data/TCGA_InfoWithGrade.csv"
31 df = pd.read_csv(url).iloc[:99, 4:9]
32 df['name'] = df.apply(lambda x: fake.name(), axis=1) # a fake name to each row
33 df = TreeviewDataFrame.transform_df(df, 'name')
34
35 # 2. Creating a TreeviewDataFrame element, and loading the prepared dataframe df during initialization:
36 cols = df.columns.to_list()
37 tree = TreeviewDataFrame(self, dataframe=df, columns=cols, show="headings")
38
39 grid(self)
40 scrollbar = ttk.Scrollbar(self, orient="vertical", command=tree.yview)
41 tree.configure(yscrollcommand=scrollbar.set)
42 frame = grid(ttk.Frame(self, padding=(2, 2)), dict(row=0, column=0, columnspan=3, sticky="e"))
43
44 # 3. Render filter and checkbox widgets:
45 grid(tree.filter_widget(frame), dict(row=0, column=0, columnspan=3, padx=5, pady=5, sticky="ew"))
46 grid(tree.checkbox_widget(frame), dict(row=3, column=0, columnspan=3, padx=5, pady=5, sticky="e"))
47
48 # 4. Render tree and scrollbar:
49 grid(tree, dict(row=1, column=0, pady=5))
50 grid(scrollbar, dict(row=1, column=2, sticky="ns"))
51
52
53app = ExampleTreeviewDataFrame()
54app.winfo_toplevel().title("Example TreeviewDataFrame")
55app.mainloop()
Further Exploration
Feel free to modify and extend these examples to fit your use case.
If you have suggestions or improvements, contribute to the project on GitHub.