1

在我的代码中有 2 个按钮 - 当我单击第一个按钮时,程序写入窗口“主页”,第二个写入窗口“搜索”并在“搜索”下创建搜索栏。我的问题是,当我两次(或多次)单击“搜索”按钮时,搜索栏也会创建更多次。我该如何解决?(我总是希望只有一个搜索栏)。

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()
4

1 回答 1

1

您所要做的就是添加一个变量,该变量表示应用程序的条目是否已创建:

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 to self.meno so you can  
                                    # access it later as an attribute
            m = Entry(self.window, textvariable=self.meno).pack()
            self.has_entry = True

更进一步,您可以改为让主页和搜索按钮控制条目小部件是否实际显示。您可以通过使用条目的.pack和方法来做到这一点:.pack_forget

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()

希望这可以帮助!

于 2014-04-20T23:59:44.367 回答