gpt4 book ai didi

Python:tkinter从类中删除对象并使其不可见

转载 作者:行者123 更新时间:2023-12-01 05:09:32 24 4
gpt4 key购买 nike

我想从另一个类中删除一个对象并使其不可见。

例如,具有名为 Button 1 的按钮的类。另一个带有名为 Button 2 的按钮的类。

当我点击按钮 2 时,我不想看到按钮 1。

from tkinter import*

class Menu(Frame):

def __init__(self,master):
Frame.__init__(self,master,bg = "white")
self.grid()
self.button_clicks = 0
self.create_widgets()

def create_widgets(self):
self.button = Button(self)
self.button["text"] = "Button 1: 0"
self.button["command"] = self.update_count
self.button.grid(ipadx = 5, padx = 150)

def update_count(self):
self.button["text"] = "Another try: " + str(self.button_clicks)
self.button_clicks += 1
if self.button_clicks > 10:
self.button_clicks = 0


class noMenu(Frame):

def __init__(self,master):
Frame.__init__(self,master,bg = "white")
self.grid()
self.button_clicks = 0
self.create_widgets()

def create_widgets(self):
self.button = Button(self)
self.button["text"] = "Bye button 1"
self.button["command"] = self.byeMenu
self.button.grid(ipadx = 5, padx = 150)

def byeMenu(self):
Menu.grid_forget()

app = Tk()
app.configure(background= "white")
app.title("Button on my but")
app.geometry("400x200")
first = Menu(app)
second = noMenu(app)
app.mainloop()

最佳答案

如果您希望小部件进行交互,请利用它们具有共同祖先的事实来实现此目的。然后,如果您希望某个小部件“消失”,您可以使用您正在使用的几何管理器来实现

可以使用的示例是:

import Tkinter

class Main(Tkinter.Tk):
def __init__(self, parent):
Tkinter.Tk.__init__(self, parent)
self.first = Menu(self)
self.second = noMenu(self)

def first_button_response(self):
self.first.button.pack_forget()

class noMenu(Tkinter.Frame):
def __init__(self, parent):
Tkinter.Frame.__init__(self, parent)
self.button = Tkinter.Button(
self, text="Bye button 1", command=parent.first_button_response
)
self.button.pack()
self.pack()

class Menu(Tkinter.Frame):
def __init__(self, parent):
Tkinter.Frame.__init__(self, parent)
self.button = Tkinter.Button(self, text="Button 1")
self.button.pack()
self.pack()


if __name__ == "__main__":
app = Main(None)
app.mainloop()

这里我使用pack_forget删除了第一个按钮。如果您想使用网格管理器,您应该查看 grid_removegrid_forget,具体取决于您是否希望在某个时候让按钮重新出现。

关于Python:tkinter从类中删除对象并使其不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24471793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com