Hide and Show frames in tkinter

John Starfire
John Starfire
13.6 هزار بار بازدید - 3 سال پیش - A slow paced tutorial about
A slow paced tutorial about showing and hiding frames with tkinter (in python) https://pythonprogramming.altervista....
Pressing the 'k' key you will hide or show the frame with the listbox on the left of the screen. We use tkinter, a built in module for python, that makes us easily create windows for apps in windows, mac os or linux. Once you understand how you can use it, it is very easy to make apps with it, as it is more confortable sometimes to us a gui app, instead of just using the command line.
We are going to create 2 frames with a listbox in each one of them. With the bind method we will bind the 'k' key with an action that destroyies the first frame when you press the k once and it will rebuild it again when you press the second time, and so on. Have fun. Giovanni Gatto.
PS: as rbende suggested in a comment, it's better to use pack_forget, instead of destroy. Take a look at the following code for the change.

import tkinter as tk

on = 1
def hide_frame():
global on, frame, lbx

if on:
 button["text"] = "+"
 frame.pack_forget()
 on = 0
else:
 button["text"] = "-"
 frame.pack_forget()
 frame1.pack_forget()
 create_frame()
 on = 1

def create_frame():
"create frame to be hidden when we press k"
global lbx, lbx1, frame, frame1

frame = tk.Frame(root)
frame.pack(side="left")
lbx = tk.Listbox(frame, bg="gold")
lbx.pack()
lbx.insert(0, 1)
frame1 = tk.Frame(root)
frame1.pack()
lbx1 = tk.Listbox(frame1, bg="cyan")
lbx1.pack(side="left")
lbx1.insert(0, 2)

root = tk.Tk()
button = tk.Button(root, text="-", command=hide_frame)
button.pack(side="left")
create_frame()
root.mainloop()
3 سال پیش در تاریخ 1400/01/05 منتشر شده است.
13,639 بـار بازدید شده
... بیشتر