python - Entry widget: avoid more than one searchbar -
in code there 2 buttons - when click on first, program writes window "home", second writes window "search" , under "search" create searchbar. problem is, when click on search button twice (or more times) searchbar created more times too. how can fix it? (i want there 1 searchbar).
from tkinter import * class app(): def __init__(self): self.window = tk() self.text=label(self.window, text="some text") self.text.pack() button_home = button(self.window, text='home',command= self.home) button_home.pack() button_search = button(self.window, text='search', command=self.search) button_search.pack() def home(self): self.text['text'] = 'home' def search(self): self.text["text"] = 'search' meno = stringvar() m = entry(self.window, textvariable=meno).pack()
all have here add variable represents whether or not application's entry has been created yet:
class app(): def __init__(self): self.window = tk() self.text=label(self.window, text="some text") self.text.pack() button_home = button(self.window, text='home',command= self.home) button_home.pack() button_search = button(self.window, text='search', command=self.search) button_search.pack() self.has_entry = false def home(self): self.text['text'] = 'home' def search(self): self.text["text"] = 'search' if not self.has_entry: self.meno = stringvar() # note - change meno self.meno can # access later attribute m = entry(self.window, textvariable=self.meno).pack() self.has_entry = true
to go further, instead make home , search buttons control whether or not entry widget displayed. using .pack
, .pack_forget
methods of entry:
class app(): def __init__(self): self.window = tk() self.text=label(self.window, text="some text") self.text.pack() button_home = button(self.window, text='home',command= self.home) button_home.pack() button_search = button(self.window, text='search', command=self.search) button_search.pack() self.meno = stringvar() self.entry = entry(self.window, textvariable=self.meno) def home(self): self.text['text'] = 'home' self.entry.pack_forget() def search(self): self.text["text"] = 'search' self.entry.pack()
hope helps!
Comments
Post a Comment