Tkinter - 帆布并排问题

时间:2017-12-30 21:49:37

标签: python canvas tkinter

我有问题将画布并排放在我的脚本上。 我想创建5个盒子,每个盒子将由用户满足销售的汽车数量,为了节省我的布局空间,我想把这5个盒子放在同一行(并排)

到目前为止,我使用下面的脚本(彼此之间的框)得到以下情况

enter image description here

    Label(self.canvas, text='North', bg="gray", fg="black").pack() 
    self.nom4=Entry(self.canvas,width=10,bg="white",\
                   fg="blue")
    self.nom4.pack()

    Label(self.canvas, text='Northeast', bg="gray", fg="black").pack() 
    self.nom5=Entry(self.canvas,width=10,bg="white",\
                   fg="blue")
    self.nom5.pack()

    Label(self.canvas, text='Midwest', bg="gray", fg="black").pack() 
    self.nom6=Entry(self.canvas,width=10,bg="white",\
                   fg="blue")
    self.nom6.pack()

    Label(self.canvas, text='Southeast', bg="gray", fg="black").pack() 
    self.nom7=Entry(self.canvas,width=10,bg="white",\
                   fg="blue")
    self.nom7.pack()

    Label(self.canvas, text='South', bg="gray", fg="black").pack() 
    self.nom8=Entry(self.canvas,width=10,bg="white",\
                   fg="blue")
    self.nom8.pack()

如何将这些盒子并排放置? 提前致谢

1 个答案:

答案 0 :(得分:2)

一种解决方案是将“框”放在Frame中并使用pack显示它们,side选项设置为'left'

from tkinter import *

root = Tk()

canvas = Canvas(root)


frame4 = Frame(canvas)
Label(frame4, text='North', bg="gray", fg="black").pack() 
nom4=Entry(frame4,width=10,bg="white", fg="blue")
nom4.pack()
frame4.pack(side='left')

frame5 = Frame(canvas)
Label(frame5, text='Northeast', bg="gray", fg="black").pack() 
nom5=Entry(frame5,width=10,bg="white", fg="blue")
nom5.pack()
frame5.pack(side='left')

frame6 = Frame(canvas)
Label(frame6, text='Midwest', bg="gray", fg="black").pack() 
nom6=Entry(frame6,width=10,bg="white", fg="blue")
nom6.pack()
frame6.pack(side='left')

frame7 = Frame(canvas)
Label(frame7, text='Southeast', bg="gray", fg="black").pack() 
nom7=Entry(frame7,width=10,bg="white", fg="blue")
nom7.pack()
frame7.pack(side='left')

frame8 = Frame(canvas)
Label(frame8, text='South', bg="gray", fg="black").pack() 
nom8=Entry(frame8,width=10,bg="white", fg="blue")
nom8.pack()
frame8.pack(side='left')


canvas.pack()

root.mainloop()

注意:这需要一个盒子类。

Box类的示例:

import tkinter as tk

class Box(tk.Frame):
    def __init__(self, master, cardinal_direction):
        super().__init__(master)

        tk.Label(self, text=cardinal_direction, bg="gray", fg="black").pack()
        self.entry = tk.Entry(self, width=10,bg="white", fg="blue")
        self.entry.pack()

if __name__ == '__main__':

    root = tk.Tk()

    canvas = tk.Canvas(root)

    boxes = dict()

    for card_dir in ['North', 'South', 'East', 'West']:
        boxes[card_dir] = Box(canvas, card_dir)
        boxes[card_dir].pack(side='left')

    canvas.pack()

    root.mainloop()