How to Create a Previous and Next Button in Tkinter with Python?

Estimated read time 2 min read

You can create Previous and Next buttons in a Tkinter window using the Button widget and keeping track of the current state or index of the data being displayed. Here’s an example code snippet:

import tkinter as tk

# sample data
data = ["Item 1", "Item 2", "Item 3", "Item 4"]

# initialize index
current_index = 0

# create tkinter window
window = tk.Tk()
window.title("Previous and Next Buttons")

# create label to display data
label = tk.Label(window, text=data[current_index])

# create Previous button
def prev():
    global current_index
    if current_index > 0:
        current_index -= 1

prev_button = tk.Button(window, text="Previous", command=prev)
prev_button.pack(side="left", padx=10)

# create Next button
def nxt():
    global current_index
    if current_index < len(data) - 1:
        current_index += 1

nxt_button = tk.Button(window, text="Next", command=nxt)
nxt_button.pack(side="right", padx=10)


In this example, we define a list of sample data data and initialize the current index current_index to 0.

We create a Tkinter window using the Tk() constructor, and add a label widget to display the current data element. We set the initial text of the label to the first element of data.

We create two button widgets for the Previous and Next buttons. We define functions prev() and nxt() to handle the button clicks. These functions update the current_index variable based on the direction of the button click and update the label text to display the new data element. We use the config() method of the label widget to update the text.

Finally, we use the pack() method to add the buttons to the window, and start the Tkinter event loop using the mainloop() method of the window object.

You can modify this code to work with your own data and customize the appearance of the window and widgets.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply