在tkinter有没有可能在同一位置拉起不同的屏幕

2024-03-29 06:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我要创建一个tkinter gui应用程序,我知道我希望它看起来怎么样。但是在玩了tkinter之后,我发现当你按下底部的按钮时,没有办法在屏幕之间切换。我知道它什么也不做,但下面是我想要的简单布局,在“myframe1”和“myframe2”之间切换,就像苹果应用商店的布局。这可能吗?在

from tkinter import *

tk = Tk()
tk.geometry("300x300")

myframe1 = Frame(tk,background="green",width=300,height=275)
myframe1.pack()

myframe2 = Frame(tk,background="cyan",width=300,height=275)
myframe2.pack()

btnframe = Frame(tk)

btn1 = Button(btnframe,text="screen1",width=9)
btn1.pack(side=LEFT)

btn2 = Button(btnframe,text="screen2",width=9)
btn2.pack(side=LEFT)

btn3 = Button(btnframe,text="screen3",width=9)
btn3.pack(side=LEFT)

btn4 = Button(btnframe,text="screen4",width=9)
btn4.pack(side=LEFT)

myframe1.pack()
btnframe.pack()

tk.mainloop()

Tags: texttkinterbutton布局widthleftframeside
2条回答

你需要开始做的事情:

def toggle(fshow,fhide):
    fhide.pack_forget()
    fshow.pack()


btn1 = Button(btnframe,text="screen1", command=lambda:toggle(myframe1,myframe2),width=9)
btn1.pack(side=LEFT)

btn2 = Button(btnframe,text="screen2",command=lambda:toggle(myframe2,myframe1),width=9)
btn2.pack(side=LEFT)

你在找一个标签式的小部件吗?您可以使用forget和{},如建议的here

下面是我在代码中使用的一个类:

class MultiPanel():
  """We want to setup a pseudo tabbed widget with three treeviews. One showing the disk, one the pile and
  the third the search results. All three treeviews should be hooked up to exactly the same event handlers
  but only one of them should be visible at any time.
  Based off http://code.activestate.com/recipes/188537/
  """
  def __init__(self, parent):
    #This is the frame that we display
    self.fr = tki.Frame(parent, bg='black')
    self.fr.pack(side='top', expand=True, fill='both')
    self.widget_list = []
    self.active_widget = None #Is an integer

  def __call__(self):
    """This returns a reference to the frame, which can be used as a parent for the widgets you push in."""
    return self.fr

  def add_widget(self, wd):
    if wd not in self.widget_list:
      self.widget_list.append(wd)
    if self.active_widget is None:
      self.set_active_widget(0)
    return len(self.widget_list) - 1 #Return the index of this widget

  def set_active_widget(self, wdn):
    if wdn >= len(self.widget_list) or wdn < 0:
      logger.error('Widget index out of range')
      return
    if self.widget_list[wdn] == self.active_widget: return
    if self.active_widget is not None: self.active_widget.forget()
    self.widget_list[wdn].pack(fill='both', expand=True)
    self.active_widget = self.widget_list[wdn]

相关问题 更多 >