Home > Software engineering >  Tkinter winfo_ismapped() method not working
Tkinter winfo_ismapped() method not working

Time:05-23

I have a program in python which in which I use Listboxes, buttons and labels. So today I came conflicting with a problem. I wanted to make my listbox appear when a button is clicked and disappear when the same button is clicked again. How can I achieve this? I tried using the winfo_ismapped() method but didnt seem to work. I think I might have done something crazy. If so, please point it out and give me a corrected answer. Else please tell me a better way to do it.

My Code:

import tkinter as tk
from tkinter import *
root = tk.Tk()
root.geometry('500x500')
def showMenu():
    overlay = Listbox(root, bg="green",  height=22, width=58)

    if overlay.winfo_ismapped() == 0:
       overlay.place(x=0,y=35)
    else:
        overlay.placeforget()

button = tk.Button(root,text="place/remove", command=showMenu)
button.place(x=0,y=0)

root.mainloop()

Actually it comes when I press the button but hide after I press it again.


In the same way I have another issue with these labels too.

CODE:

import tkinter as tk

root = tk.Tk()

def placeFun():
    successtext = tk.Label(root, text="Success", anchor='nw',  bg="#212121", fg="#ff3300",font=("Consolas", 15, "bold"))
    if successtext.winfo_ismapped() == 0:
       successtext.place(x=0,y=50)
    else:
        succestext.forget()

button = tk.Button(root, text='place/rem', width=25, command=placeFun)
button.place(x=0,y=0)

root.mainloop()

Please Note: I want a professional way to handle this, I said it because, I know a way in which we use variables like:

globalvartimes = 0

def somefunc():
  if times % 2 == 0:
    show the listbox
    global times
    times  = 2
  else:
    remove the listbox
    times  = 1

*This shows the listbox when times is even and remove it when it's odd.
These makes the code look non-professional and long.

CodePudding user response:

The problem is every time showMenu() is called another Listbox is created. To fix that, create the Listbox outside of the function (so it's a global).

(I also noticed you misspelled the name of place_forget() method.)

import tkinter as tk
from tkinter import *

root = tk.Tk()
root.geometry('500x500')

def showMenu():
    if overlay.winfo_ismapped() == 0:
       overlay.place(x=0,y=35)
    else:
        overlay.place_forget()

overlay = Listbox(root, bg="green",  height=22, width=58)

button = tk.Button(root,text="place/remove", command=showMenu)
button.place(x=0,y=0)

root.mainloop()

This looks like it is what is wrong with your Label example, too.

Note: If you want to write "professional" code, I suggest you read (and start following) the
PEP 8 - Style Guide for Python Code.

  • Related