Python Tkinter开发如何实现点击任一按钮后隐藏所有已存在按钮
解决方案
你的需求可以通过以下调整实现,核心逻辑是将两个按钮保存为类的实例属性,让事件回调方法可以同时访问到两个按钮对象,再同步执行隐藏操作:
- 调整按钮创建逻辑,将两个按钮绑定为类的实例属性,同时修正第二个按钮的鼠标事件绑定(原代码绑定的是
<Button-2>即鼠标中键,不符合常规左键点击的交互习惯),另外补充你代码中遗漏的position参数传值/移除无用参数
- 调整按钮创建逻辑,将两个按钮绑定为类的实例属性,同时修正第二个按钮的鼠标事件绑定(原代码绑定的是
- 修改点击事件的回调方法,同时对两个按钮执行
pack_forget()操作
- 修改点击事件的回调方法,同时对两个按钮执行
- 额外提示:如果你的frame对象是局部变量,建议也调整为实例属性
self.frame,避免作用域问题导致按钮创建失败
修正后的完整代码
首先是事件回调部分:
def p1Choice_a(self, event): print("You choose to run from the big wolf") # 同时隐藏两个按钮 self.p1ca.pack_forget() self.p1cb.pack_forget() def p1Choice_b(self, event): print("You choose to talk the big wolf") # 同时隐藏两个按钮 self.p1ca.pack_forget() self.p1cb.pack_forget()
然后是按钮创建及启动部分:
def start(self): # 如果你不需要用到position参数可以直接删掉方法定义里的形参,这里示例直接传None self.create_button_p1(position=None) def create_button_p1(self, position): # 将按钮保存为实例属性 self.p1ca = Button(frame, text="A. Run from the big wolf") self.p1ca.bind('<Button-1>', self.p1Choice_a) self.p1ca.pack( side = LEFT ) self.p1cb = Button(frame, text="B. Have a conversation with the big wolf") # 修正为左键点击触发 self.p1cb.bind('<Button-1>', self.p1Choice_b) self.p1cb.pack( side = RIGHT ) rrhStart = RedRidingHood() rrhStart.start()
如果后续你需要重新显示这两个按钮,直接调用self.p1ca.pack()和self.p1cb.pack()即可恢复。
内容的提问来源于stack exchange,提问作者Nics Reyes
相关产品推荐
相关产品推荐

