Python:GUI打包小部件

时间:2014-03-20 03:42:14

标签: python tkinter pack

这是我的程序,我打包我的小部件,所以它会被留下但不知何故,当我运行它时,小部件不会从左侧出现。人和颜色出现在中间,但可怕的人和动物出现在左边。我也希望人物和颜色小部件出现在左侧。

这是我的程序

from Tkinter import *
import Tkinter
import tkMessageBox 

class StoryMaker:

 def __init__(self):

  # Create the main window.
  self.main_window = Tkinter.Tk()

  #Create nine frames to group widgets.
  self.first_frame = Tkinter.Frame()
  self.second_frame = Tkinter.Frame() 
  self.third_frame = Tkinter.Frame()
  self.fourth_frame = Tkinter.Frame()
  self.fifth_frame = Tkinter.Frame()

  # Create the widgets for the first frame. 
  self.prompt_label = Tkinter.Label(self.first_frame, text='Please enter information for a new story, then click the "Make Story" button.')

  # Create the widgets for the second frame.
  self.person_label = Tkinter.Label(self.second_frame, text='Person: ')
  self.person_entry = Tkinter.Entry(self.second_frame, width= 15)

  # Pack the second frame's widgets.
  self.person_label.pack(side='left')
  self.person_entry.pack(side='left')

  # Create the widgets for the third frame.
  self.colour_label = Tkinter.Label(self.third_frame, text='Colour: ')
  self.colour_entry = Tkinter.Entry(self.third_frame, width= 15)

  # Pack the third frame's widgets.
  self.colour_label.pack(side='left')
  self.colour_entry.pack(side='left')

  # Create the widgets for the fourth frame.
  self.scary_label = Tkinter.Label(self.fourth_frame, text='Scary person or creature: ', justify=LEFT)
  self.scary_entry = Tkinter.Entry(self.fourth_frame, width= 15)

  # Pack the fourth frame's widgets.
  self.scary_label.pack(side='left')
  self.scary_entry.pack(side='left')

  # Pack the frames.
  self.first_frame.pack()
  self.second_frame.pack()
  self.third_frame.pack()
  self.fourth_frame.pack() 
  self.fifth_frame.pack()

  # Enter the Tkinter main loop.
  Tkinter.mainloop()

 my_gui = StoryMaker()

1 个答案:

答案 0 :(得分:1)

我建议的第一件事是你给每个框架一个不同的背景颜色。这只是暂时的,因此您可以看到每个帧的开始和结束位置。我认为你会发现结果令人惊讶:

 self.first_frame = Tkinter.Frame(background="red")
 self.second_frame = Tkinter.Frame(background="pink") 
 self.third_frame = Tkinter.Frame(background="green")
 self.fourth_frame = Tkinter.Frame(background="blue")
 self.fifth_frame = Tkinter.Frame(background="yellow")

当你这样做时,你会很快发现问题不是标签居中,而是它们所在的框架位于中心。这是因为你打包它们没有选项,这与说...pack(side="top", fill=None, expand=False)相同。

如果您在打包fill="x"first_frame等时添加second_frame),您会看到您的标签和条目小部件确实位于其容器的左侧。

我对那些试图学习tkinter的人的建议是采取分裂和征服的方式。做法。如果您使用中间框架来组织窗口小部件,请首先创建 这些框架。获取包或网格选项集,以便包含小部件的小部件位于您想要的位置,并按照您希望的方式调整大小。只有在这样做之后才应该添加内部小部件。这样,在任何时候你都只是试图一次解决一组小部件的布局问题。

如果您正在布置表单,您可能会发现使用网格而不是打包更容易。通常在一种形式中,一组标签中的所有标签将具有相同的尺寸并且彼此对齐。通过使用网格并将所有小部件放在单个帧中比使用多个帧更容易。

相关问题