Python Tkinter Filter Function() – How to use

In this Python Tkinter tutorial, we will learn how to use filter function in Python Tkinter with different examples related to the Tkinter filter. And we will cover these topics.

  • Python Tkinter Filter date between two dates
  • Python Tkinter Treeview Filter
  • Python Tkinter file Dialog Filter
  • Python Tkinter Listbox filter

Python Tkinter filter date between two dates

In this section, we will learn how to filter dates between two dates in Python Tkinter.

Filter() method filters the series they can filter all elements present in the series.

The items filter through function and test the item is accepted or not if the item is not accepted its shows an error message. In this, we can filter date between two dates

Code:

In the following code, we import libraries datetime import date, datetime import timedelta. timedelta() function is used for calculating the difference between the dates.

date.today() is used for showing the present date.

from tkinter import *



from datetime import date
from datetime import timedelta


today1 = date.today()
print("Today is: ", today1)


yesterday1 = today1 - timedelta(days = 1)
print("Yesterday was: ", yesterday1)

Output:

After running the above code we get the following output we see the filter dates between two dates.

Python Tkinter filter date and time
Python Tkinter filter date and time Output

Read Python Tkinter add function

Python Tkinter Treeview Filter

In this section, we will learn how to create a treeview filter in Python Tkinter.

Treeview refers to hierarchical representation we can use filter treeview which can filter all the rows of the treeview. It can test the item of the treeview that the user chooses the item is present in the treeview or not.

READ:  module 'matplotlib' has no attribute 'plot'

Code:

In the following code, we import the panda’s library. Pandas are used for analyzing the data.

  • tkinter.ttk module is used to obtain Python Tkinter treeview.
  • ttk.Combobox() is a combination of list items it shows the dropdown menu.
from tkinter import *
import pandas as pd
from tkinter import ttk

df = pd.DataFrame({"currency":["EUR","XCD","ARS","CAD"],
                   "volumne":[400,500,600,700]})

class app(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.title("Python Guides")

        self.tree = ttk.Treeview(self)
        columns = list(df.columns)
        self.Combo = ttk.Combobox(self, values=list(df["currency"].unique()),state="readonly")
        self.Combo.pack()
        self.Combo.bind("<<ComboboxSelected>>", self.select_currency)
        self.tree["columns"] = columns
        self.tree.pack(expand=TRUE, fill=BOTH)

        for i in columns:
            self.tree.column(i, anchor="w")
            self.tree.heading(i, text=i, anchor="w")

        for index, row in df.iterrows():
            self.tree.insert("", "end", text=index, values=list(row))

    def select_currency(self,event=None):
        self.tree.delete(*self.tree.get_children())
        for index, row in df.loc[df["currency"].eq(self.Combo.get())].iterrows():
            self.tree.insert("", "end", text=index, values=list(row))

ws = app()
ws.mainloop()

Output:

In the following output, we see a simple Tkinter treeview is displayed. In which there are four rows and two columns.

Python Tkinter treeview filter
Python Tkinter Treeview filter Output

In this picture, we see the user selects the currency after selecting the filter method to verify that the currency is present in the list or not. If present it shows the result as we have shown.

Treeview filter in Python Tkinter
Python Tkinter Treeview filter

Read Python Tkinter panel

Python Tkinter File Dialog Filter

In this section, we will learn how to create a dialog filter in Python Tkinter.

File dialog filter determines what type of files are displayed from the dialog box. The user chooses the file from the dialog box if the file is present in the dialog it shows the file location if the file is not selected it shows a pop-up msg select file.

Code:

In the following code, we import some libraries such as from Tkinter import filedialog as fd and from tkinter.messagebox import showinfo.

  • fd.askopenfilename() is used to show a dialog box and allow to choosing a file from the file system.
  • showinfo() is used for giving a popup message on the window.
from tkinter import *
from tkinter import filedialog as fd
from tkinter.messagebox import showinfo

ws = Tk()
ws.title('Python Guides')
ws.resizable(False, False)
ws.geometry('500x300')

def selectfile():
    filetypes = (
        ('text files', '*.txt'),
        ('All files', '*Allfile*')
    )

    filename = fd.askopenfilename(
        title='open file',
        initialdir='/',
        filetypes=filetypes)

    showinfo(
        title='Python Guides',
        message=filename
    )

button = Button(
    ws,
    text='Open File',
    command=selectfile
)

button.pack(expand=True)

ws.mainloop()

Output:

READ:  Django for loop

In the following output, we see a widget inside the widget a button is created.

Python tkinter file dialog filter
Python tkinter file dialog filter

On clicking on the button a dialog box is open. From this dialog box, we select a file. After selecting a file click on open.

file dialog filter Python Tkinter
Python Tkinter file dialog filter

After click on open, we get the path where the file is located after filtering this.

Python tkinter file dialog filter eexample
Python Tkinter filedialog filter

Read Python Tkinter after method

Python Tkinter Listbox Filter

In this section, we will learn how we can create a Listbox filter in Python Tkinter.

By Listbox filter, we mean to filter the result from inside a list which we can use with help of a search box that helps to filter our content and also show our results.

Code:

In the following code, we created a list box with help of the list.insert() we inserted some values inside a list that is visible to us inside a box and to filter these values, we added a filter box where a user type for an item that user want to look inside a listbox.

listbox.insert() is used to insert the values inside a list

list = (‘Value,’value1’)

from tkinter import *

def Scankey(event):
	
	val = event.widget.get()
	print(val)
	
	if val == '':
		data = list
	else:
		data = []
		for item in list:
			if val.lower() in item.lower():
				data.append(item)				
	
	Update(data)
def Update(data):
	
	listbox.delete(0, 'end')
	
	for item in data:
		listbox.insert('end', item)

list = ('Salt','Sugar','Oil',
	'Toothpaste','Rice',
	'Pens','Fevicol','Notebooks' )

ws = Tk()
ws.title("Python Guides")
ws.geometry("500x300")


entry = Entry(ws)
entry.pack()
entry.bind('<KeyRelease>', Scankey)


listbox = Listbox(ws)
listbox.pack()
Update(list)

ws.mainloop()

Output:

After running the above code, we can see the following output which helps to describe the Listbox filter. Here, Inside a window, a list box is created with some pre-defined items and a filter box.

Python tkinter listbox filter
Python Tkinter Listbox Filter Output

As in the below output, we can see a user is using some attributes to filter some items inside a Listbox and the function of filtering inside a Listbox is working properly and defining the results.

Python tkinter listbox filter
Python Tkinter Listbox Filter Output

Related Posts:

READ:  Python Turtle Background + Examples

So, in this tutorial, we discussed the Python Tkinter filter and we have also covered different examples. Here is the list of examples that we have covered.

  • python Tkinter filter date between two dates
  • python Tkinter treeview filter
  • python Tkinter file dialog filter
  • python Tkinter Listbox filter