Pythons .grid()函数如何工作

时间:2015-01-29 22:10:49

标签: python tkinter grid-layout

我尝试使用以下对齐按钮,但它不起作用

#creates entry inputs for answers
entry=Entry(master)
entry.pack()
entry.focus_set() 

#button 1 created and used to call addition function
b1 = Button(master, text="+", command=callback)
b1.pack(side=LEFT)

#button 2 created and used to call subtraction function
b2 = Button(master, text="-", command=callback2)
b2.pack(side=LEFT)

#button 3 created and used to call divison function
b3 = Button(master, text="/", command=callback3)
b3.pack(side=LEFT)

#button 4 created and used to call multiplication function
b4 = Button(master, text="*", command=callback4)
b4.pack(side=LEFT)

#button 5 created and used to check answers
b5 = Button(master, text="Check Ans", width=10, command=callbackinput)
b5.pack(side=LEFT)

编辑我正试图让一个条目坐在中间位于左侧四个按钮上方

我到目前为止(image)需要对齐按钮上方的条目

当使用.grid(row =,column =)时,GUI不会出现

2 个答案:

答案 0 :(得分:2)

由于您使用pack作为几何管理器,因此当您在其中一个按钮上调用grid时,tkinter不知道该怎么做。选择一个几何管理器并在整个窗口中坚持使用它。

from tkinter import *

master = Tk()

# some dummy callback functions
callback, callback2, callback3, callback4, callbackinput = [lambda: None]*5    

#creates entry inputs for answers
entry=Entry(master)
entry.grid(row=0, column=0, columnspan=6)
entry.focus_set() 

#button 1 created and used to call addition function
b1 = Button(master, text="+", command=callback)
b1.grid(row=1, column=0)

#button 2 created and used to call subtraction function
b2 = Button(master, text="-", command=callback2)
b2.grid(row=1, column=1)

#button 3 created and used to call divison function
b3 = Button(master, text="/", command=callback3)
b3.grid(row=1, column=2)

#button 4 created and used to call multiplication function
b4 = Button(master, text="*", command=callback4)
b4.grid(row=1, column=3)

#button 5 created and used to check answers
b5 = Button(master, text="Check Ans", width=10, command=callbackinput)
b5.grid(row=1, column=4, columnspan=2)

创建一个如下所示的窗口:

Tk window

答案 1 :(得分:1)

您的代码中存在的问题是,您同时呼叫gridpack。 Tkinter有三个几何管理器:那两个,加上place。窗口小部件一次只能由其中一个控制。当您拨打多个电话时,它只是最后一个有效的电话。因此,当您致电grid时,对pack的调用产生的任何影响均无效。